DOC PREVIEW
UMD CMSC 132 - Java Exceptions, Cloning, Serialization

This preview shows page 1-2-3-4-5-6 out of 18 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 18 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 18 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 18 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 18 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 18 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 18 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 18 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

1Java Exceptions, Cloning, SerializationNelson Padua-PerezChau-Wen TsengDepartment of Computer ScienceUniversity of Maryland, College ParkOverviewReviewErrorsExceptionsJava supportRepresenting exceptionsGenerating & handling exceptionsDesigning & using exceptions2Types of Program Errors1. Syntax (compiler) errorsErrors in code construction (grammar, types)Detected during compilation2. Run-time errorsOperations illegal / impossible to executeDetected during program executionTreated as exceptions in Java3. Logic errorsOperations leading to incorrect program stateMay (or may not) lead to run-time errorsDetect by debugging codeException HandlingPerforming action in response to exceptionExample actionsIgnore exceptionPrint error messageRequest new dataRetry actionApproaches1. Exit program2. Exit method returning error code3. Throw exception3ProblemMay not be able to handle error locallyNot enough information in method / classNeed more information to decide actionHandle exception in calling function(s) insteadDecide at application level (instead of library)ExamplesIncorrect data format ⇒ ask user to reenter data Unable to open file ⇒ ask user for new filenameInsufficient disk space ⇒ ask user to delete filesWill need to propagate exception to caller(s)Exception Handling – Exit ProgramApproachExit program with error message / error codeExampleif (error) {System.err.println(“Error found”); // messageSystem.exit(1); // error code}ProblemDrastic solutionEvent must be handled by user invoking programProgram may be able to deal with some exceptions4Exception Handling – Error CodeApproachExit function with return value ⇒ error codeExampleA( ) { if (error) return (-1); }B( ) { if ((retval = A( )) == -1) return (-1); }ProblemsCalling function must check & process error codeMay forget to handle error codeMay need to return error code to callerAgreement needed on meaning of error codeError handling code mixed with normal codeException Handling – Throw ExceptionApproachThrow exception (caught in parent’s catch block)ExampleA( ) { if (error) throw new ExceptionType(); }B( ) { try { A( ); } catch (ExceptionType e) { ...action... } }Java exception backtracks to caller(s) until matching catch block found5Exception Handling – Throw ExceptionAdvantagesCompiler ensures exceptions are caught eventuallyNo need to explicitly propagate exception to callerBacktrack to caller(s) automaticallyClass hierarchy defines meaning of exceptionsNo need for separate definition of error codesException handling code separate & clearly markedRepresenting ExceptionsExceptions represented asObjects derived from class ThrowableCodepublic class Throwable( ) extends Object {Throwable( ) // No error messageThrowable( String mesg ) // Error messageString getMessage() // Return error mesgvoid printStackTrace( ) { … } // Record methods… // called & location}6Representing ExceptionsJava Exception class hierarchyTwo types of exceptions ⇒ checked & uncheckedObjectObjectErrorErrorThrowableThrowableExceptionExceptionLinkageErrorLinkageErrorVirtualMachoneErrorVirtualMachoneErrorClassNotFoundExceptionClassNotFoundExceptionCloneNotSupportedExceptionCloneNotSupportedExceptionIOExceptionIOExceptionAWTErrorAWTError…AWTExceptionAWTExceptionRuntimeExceptionRuntimeException…ArithmeticExceptionArithmeticExceptionNullPointerExceptionNullPointerExceptionIndexOutOfBoundsExceptionIndexOutOfBoundsExceptionUncheckedUncheckedCheckedCheckedNoSuchElementExceptionNoSuchElementException…Representing ExceptionsJava Exception class hierarchy7Unchecked ExceptionsClass Error & RunTimeExceptionSerious errors not handled by typical programUsually indicate logic errorsExampleNullPointerException, IndexOutOfBoundsExceptionCatching unchecked exceptions is optionalHandled by Java Virtual Machine if not caughtChecked ExceptionsClass Exception (except RunTimeException)Errors typical program should handleUsed for operations prone to errorExampleIOException, ClassNotFoundExceptionCompiler requires “catch or declare” Catch and handle exception in method, ORDeclare method can throw exception, force calling function to catch or declare exception in turnExamplevoid A( ) throws ExceptionType { … }8Generating & Handling ExceptionsJava primitivesTryThrowCatchFinallyProcedure for using exceptions1. Enclose code generating exceptions in try block2. Use throw to actually generate exception3. Use catch to specify exception handlers4. Use finally to specify actions after exceptionJava Syntaxtry { // try block encloses throwsthrow new eType1(); // throw jumps to catch}catch (eType1 e) { // catch block 1...action... // run if type match} catch (eType2 e) { // catch block 2...action... // run if type match} finally { // final block...action... // always executes}9Java Primitive – TryForms try blockEncloses all statements that may throw exceptionScope of try block is dynamicIncludes code executed by methods invoked in try block (and their descendents)Java Primitive – TryExampletry { // try block encloses all exceptions in A & BA( ); // exceptions may be caught internally in A & BB( ); // or propagated back to caller’s try block}void A( ) throws Exception { // declares exceptionB( );}void B( ) throws Exception { // declares exceptionthrow new Exception( ); // propagate to caller}10Java Primitive – ThrowIndicates exception occurredNormally specifies one operandObject of class ExceptionWhen an exception is thrown1. Control exits the try block 2. Proceeds to closest matching exception handler after the try block3. Execute code in exception handler4. Execute code in final block (if present)Java Primitive – CatchPlaced after try blockSpecifies code to be executed for exceptionCode in catch block ⇒ exception handlerCatch block specifies matching exception typeCan use multiple catch blocks for single tryTo process different types of exceptionsFirst matching catch block executedSuperclass may subsume catch for subclassIf catch block for superclass occurs first11Java Primitive – CatchExampleclass eType1 extends Exception { … }try {… throw new eType1( ) …}catch (Exception e) { // Catch block 1...action... // matches all exceptions} catch (eType1 e) { // Catch block 2...action... // matches eType1} // subsumed by block 1// will never be executedJava Primitive – CatchCan rethrow exceptionException propagated to caller(s)Examplecatch (ExceptionType e) {… // local action for exceptionthrow e; // rethrow exception } //


View Full Document

UMD CMSC 132 - Java Exceptions, Cloning, Serialization

Documents in this Course
Notes

Notes

8 pages

Recursion

Recursion

12 pages

Sorting

Sorting

31 pages

HTML

HTML

7 pages

Trees

Trees

19 pages

HTML

HTML

18 pages

Trees

Trees

19 pages

Honors

Honors

19 pages

Lecture 1

Lecture 1

11 pages

Quiz #3

Quiz #3

2 pages

Hashing

Hashing

21 pages

Load more
Download Java Exceptions, Cloning, Serialization
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Java Exceptions, Cloning, Serialization and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Java Exceptions, Cloning, Serialization 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?