Fundamentals of computing 1 - Lecture title: Exception handling

Errors Exception Handing in Java try – catch block Multiple catch block Nested try statements Finally block Throw keyword Throws keyword Exception Handling in Method Overriding Custom Exception

ppt71 trang | Chia sẻ: nguyenlam99 | Lượt xem: 900 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Fundamentals of computing 1 - Lecture title: Exception handling, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
Lecture Title: Exception HandlingFundamentals of Computing 1AgendaErrorsException Handing in Javatry – catch blockMultiple catch blockNested try statementsFinally blockThrow keywordThrows keywordException Handling in Method OverridingCustom ExceptionErrorsThree categories of errors: Syntax errors (compile error)Logic errorsRuntime errorsSyntax errorsSyntax errors arise because the rules of the language have not been followed. They are detected by the compiler. Logic errorsLogic errors occur when a program doesn't perform the way it was intended to. Runtime errorsRuntime errors occur while the program is terminated when the environment detects an operation that is impossible to carry out. Runtime Errors (cont.)Catch Runtime ErrorsAgendaErrorsException Handing in Javatry – catch blockMultiple catch blockNested try statementsFinally blockThrow keywordThrows keywordException Handling in Method OverridingCustom ExceptionException Handing in JavaThe exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the runtime errors. In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime. Exception ClassesSystem ErrorsSystem errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully. ExceptionsException describes errors caused by your program and external circumstances. These errors can be caught and handled by your program. Runtime ExceptionsRuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.Checked Exceptions vs. Unchecked ExceptionsRuntimeException, Error and their subclasses are known as unchecked exceptions. All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with the exceptions. Unchecked ExceptionsUnchecked exception.Example: ArithmeticExceptionWhen method divide() is invoked and iaf users input zero number for b, there occurs an ArithmeticException.Example: NullPointerExceptionInvoke method nullPointer(), there occurs NullPointerException.Example: ArrayIndexOutOfBoundsExceptionInvoke method indexOfBound(), there occurs ArrayIndexOutOfBoundException.Example: NumberFormatExceptionWhen users input the value for string variable that have characters, converting this variable into digit will occur NumberFormatException. Five keywords used in Exception handling:try catch finally throw throws AgendaErrorsException Handing in Javatry – catch blockMultiple catch blockNested try statementsFinally blockThrow keywordThrows keywordException Handling in Method OverridingCustom Exceptiontry catch block Enclose the code that might throw an exception in try blockCatch block is used to handle the Exception.Syntax of try with catch blockProblem without exception handling The statement System.out.println(a+b) is not executed i.e. the value of (a+b)... is not printed. What happen behind code a=a/bBut if exception is handled by application programmer, normal flow of the application is maintained, i.e the statement System.out.println(a+b) is excuted a=a/ban object of exception class is thrownis handled?Exception objectSystem.out.println(a+b)is excutedJVMPrints out exception descriptionPrints the stack traceTerminates the programyesnoSolution by exception handling Now, System.out.println(a+b) is executed, i.e. the value of (a +b) is printed. Output:AgendaErrorsException Handing in Javatry – catch blockMultiple catch blockNested try statementsFinally blockThrow keywordThrows keywordException Handling in Method OverridingCustom ExceptionMultiple catch block If you have to perform different tasks at the occurrence of different Exceptions, use multiple catch block. OutputMultiple catch block (cont.)Rule: At a time only one Exception is occurred and at a time only one catch block is executed.Multiple catch block - CautionException subclass must come before any of their superclassesA catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses. So, the subclass would never be reached if it come after its superclassFor example, ArithmeticException is a subclass of ExceptionMoreover, unreachable code in Java generates errorMultiple catch block - ExampleAgendaErrorsException Handing in Javatry – catch blockMultiple catch blockNested try statementsFinally blockThrow keywordThrows keywordException Handling in Method OverridingCustom ExceptionNested try statementsA try statement can be inside the block of another try Each time a try statement is entered, the context of that exception is pushed on the stackIf an inner try statement does not have a catch, then the next try statement’s catch handlers are inspected for a matchIf a method call within a try block has try block within it, then then it is still nested tryNested try Statements - ExampleAgendaErrorsException Handing in Javatry – catch blockMultiple catch blockNested try statementsFinally blockThrow keywordThrows keywordException Handling in Method OverridingCustom ExceptionThe finally Blocktry { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }Trace a Program Executiontry { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }Next statement;Suppose no exceptions in the statementsTrace a Program Executiontry { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }Next statement;The final block is always executedTrace a Program Executiontry { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }Next statement;Next statement in the method is executedTrace a Program Executiontry { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }Next statement;Suppose an exception of type Exception1 is thrown in statement2Trace a Program Executiontry { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }Next statement;The exception is handled.Trace a Program Executiontry { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }Next statement;The final block is always executed.Trace a Program Executiontry { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }Next statement;The next statement in the method is now executed.Trace a Program Executiontry { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements; }Next statement;statement2 throws an exception of type Exception2.Trace a Program Executiontry { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements; }Next statement;Handling exceptionTrace a Program Executiontry { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements; }Next statement;Execute the final blockTrace a Program Executiontry { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements; }Next statement;Next statement in the method is executedTrace a Program Executiontry { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements; }Next statement;Rethrow the exception and control is transferred to the callerAgendaErrorsException Handing in Javatry – catch blockMultiple catch blockNested try statementsFinally blockThrow keywordThrows keywordException Handling in Method OverridingCustom ExceptionThrow keyword Throw keyword is used to explicitly throw an exception. We can throw either checked or unchecked exception. But checked exception must be propagated with throws keywordThe throw keyword is mainly used to throw custom exception. We will see custom exceptions later.Throw keyword with unchecked exceptionIn this example, we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message “welcome to vote”. Output: AgendaErrorsException Handing in Javatry – catch blockMultiple catch blockNested try statementsFinally blockThrow keywordThrows keywordException Handling in Method OverridingCustom ExceptionThrows keyword The throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing check up before the code being used.Syntax of throws keyword: Which exception should we declare Checked exception only, because: unchecked Exception: under your control so correct your code. error: beyond your control e.g. you are unable to do anything if there occurs VirtualMachineError or StackOverflowError. Throw and Throws keyword with checked exceptionOutput: Difference between throw and throws 1) Throw is used to explicitly throw an exception.Throws is used to declare an exception.2) Unchecked exception can not be propagated without throws.Checked exception can be propagated with throws.3) Throw is followed by an instance.Throws is followed by class.4) Throw is used within the method.Throws is used with the method signature.5) You cannot throw multiple exceptionYou can declare multiple exception e.g.public void method()throws IOException,SQLException Can we rethrow an exception Yes by throwing same exception in catch block AgendaErrorsException Handing in Javatry – catch blockMultiple catch blockNested try statementsFinally blockThrow keywordThrows keywordException Handling in Method OverridingCustom ExceptionExceptionHandling with MethodOverriding If the superclass method does not declare an exception If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception. If the superclass method declares an exception If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception. If the superclass method does not declare an exception Rule: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but can declare unchecked exception. If the superclass method does not declare an exception (cont.)Rule: If the superclass method does not declare an exception, subclass overridden method cannot declare a checked exception. Output:Compile Time Error If the superclass method does not declare an exception (cont.)Rule: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but can declare unchecked exception. Output: child If the superclass method declares an exception Rule: If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception. Example in case subclass overridden method declares same exceptionOutput: child Example in case subclass overridden method declares subclass exceptionOutput: child Example in case subclass overridden method declares no exceptionOutput: child Example in case subclass overridden method declares parent exceptionOutput: Compile Time Error AgendaErrorsException Handing in Javatry – catch blockMultiple catch blockNested try statementsFinally blockThrow keywordThrows keywordException Handling in Method OverridingCustom ExceptionCustom Exception If you are creating your own Exception that is known as custom exception or user-defined exception. Example of custom exception Output: What we have coveredErrorsException Handing in Javatry – catch blockMultiple catch blockNested try statementsFinally blockThrow keywordThrows keywordException Handling in Method OverridingCustom Exception

Các file đính kèm theo tài liệu này:

  • pptlecture_12_exception_handling_0839.ppt