Java Exceptions, Cloning, SerializationOverviewTypes of Program ErrorsException HandlingProblemException Handling – Exit ProgramException Handling – Error CodeException Handling – Throw ExceptionSlide 9Representing ExceptionsSlide 11Slide 12Unchecked ExceptionsChecked ExceptionsGenerating & Handling ExceptionsJava SyntaxJava Primitive – TrySlide 18Java Primitive – ThrowJava Primitive – CatchSlide 21Slide 22Java Primitive – FinallyDesigning & Using ExceptionsSlide 25Exceptions SummarySlide 27Java – CloningSlide 29Java Clone ComparisonSlide 31Slide 32Java – SerializabilitySerializability – UsesSerializability – Deep CopyJava Serializable ComparisonJava Exceptions, Cloning, SerializationNelson Padua-PerezChau-Wen TsengDepartment of Computer ScienceUniversity of Maryland, College ParkOverviewReviewErrorsExceptionsJava supportRepresenting exceptionsGenerating & handling exceptionsDesigning & using exceptionsTypes 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 exceptionProblemMay 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”); // message System.exit(1); // error code}ProblemDrastic solutionEvent must be handled by user invoking programProgram may be able to deal with some exceptionsException 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 foundException 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 message Throwable( String mesg ) // Error message String getMessage() // Return error mesg void printStackTrace( ) { … } // Record methods … // called & location}Representing ExceptionsJava Exception class hierarchyTwo types of exceptions checked & uncheckedObjectObjectErrorErrorThrowableThrowableExceptionExceptionLinkageErrorLinkageErrorVirtualMachoneErrorVirtualMachoneErrorClassNotFoundExceptionClassNotFoundExceptionCloneNotSupportedExceptionCloneNotSupportedExceptionIOExceptionIOExceptionAWTErrorAWTError…AWTExceptionAWTExceptionRuntimeExceptionRuntimeException…ArithmeticExceptionArithmeticExceptionNullPointerExceptionNullPointerExceptionIndexOutOfBoundsExceptionIndexOutOfBoundsExceptionUncheckedUncheckedCheckedCheckedNoSuchElementExceptionNoSuchElementException…Representing ExceptionsJava Exception class hierarchyUnchecked 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 errorExample IOException, 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 { … }Generating & 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 throws throw 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}Java 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 & B A( ); // exceptions may be caught internally in A & B B( ); // or propagated back to caller’s try block}void A( ) throws Exception { // declares exception B( );}void B( ) throws Exception { // declares exception throw new Exception( ); // propagate to caller}Java 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
View Full Document