1 / 43

Exception Handling

Exception Handling. CISC6795, Spring 2011. Introduction. Exception – an indication of a problem that occurs during a program’s execution, for examples: ArrayIndexOutOfBoundsException – an attempt is made to access an element past end of an array

laraj
Download Presentation

Exception Handling

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Exception Handling • CISC6795, Spring 2011

  2. Introduction • Exception – an indication of a problem that occurs during a program’s execution, for examples: • ArrayIndexOutOfBoundsException – an attempt is made to access an element past end of an array • ClassCastException – an attempt is made to cast an object that does not have an is-a relationship with type specified in cast operator • ArithmeticException – can arise from a number of different problems in arithmetic • InputMismatchException – occurs when Scanner method nextInt receives a string that does not represent a valid integer • Exception handling – resolving exceptions that may occur so program can continue or terminate gracefully

  3. Attempt to divide; denominator may be zero Read input; exception occurs if input is not a valid integer

  4. Outline

  5. Exception-Handling Overview • Traditional way to handle various error condition: • Check for error condition returned by return value, and process it • Intermixing program logic with error-handling logic • can make programs difficult to read, modify, maintain and debug • If potential problems occur infrequently, degrade a program’s performance

  6. Exception-Handling Overview • Exception handling enables programmers to remove error-handling code from the “main line” of program’s execution • Improves clarity • Enhances modifiability • Language mechanisms: • Extensible exception hierarchy (exception is a class) • throw exceptions: to generate an exception object to indicate an error condition • try block: to enclose codes that might throw exceptions • catch block: to handle exception

  7. try statement • try statement : onetry block and corresponding catch and/or finally blocks • Possible multiple catch blocks, each catching a particular type of exception • NO code between a try block and its corresponding catch blocks. • Cannot catch same type of exception in two different catch blocks • Uncaught exception – an exception that occurs for which there are no matching catch blocks

  8. try block attempts to read input and perform division throws clause specifies that method quotient may throw an ArithmeticException Outline

  9. Call method quotient, which may throw ArithmeticException Exception parameters • Standard streams: • System.out – standard output stream, System.err – standard error stream • Both by default are linked to command terminal • print,println , printf methods

  10. Enclosing Code in a try Block • try block –keyword try followed by a block of code • encloses code that might throw an exception and subsequent code that should not execute if exception occurs • E.g., if open file calls fails, should not continue to read file … • E.g., if reading from standard input failed, should not process input… • Throw point of an exception: the statement that leads to the exception, it can be • A throw statement • calls to other method that throw an exception • deeply nested method calls initiated by code in a try block • from Java Virtual Machine as it executes Java bytecodes. • Do not placetry...Catch…finally... around every statement that may throw an exception.

  11. Catch block • catch block – catches and handles an exception catch (ArithmeticException exception) { } • keyword catch, followed by exception parameter in parentheses – which identifies exception type and name, • Each catch block can have only a single parameter • followed by block of code in curly braces that executes when exception of specified type occurs • Display the caught exceptions • Prompt user to try again, or clean up before terminating program

  12. finally block • finally block, optional in the try statement • finally keyword followed by a block of code • Executes whether or not an exception is thrown in try block or any of its corresponding catch blocks • Will not execute if application exits early from a try block via method System.exit • Typically contains resource-release code to avoid resource leaks • E.g., finally block should close any files opened in try block.

  13. Program control in Exception Handling • Execute statements in try block • If no exception occurs: • Skip catch blocks to finally block. • After executing finally block, control proceeds to first statement after finally block. • If an exception occurs: • Skips rest of try block. • First matching catch block executes • If no matching catch blocks, control proceeds to finally block, and then passes exception to next outer try block • If catch block throws an exception, finally block still executes • finally block executes. • Control proceeds to first statement after finally block

  14. try block attempts to read input and perform division throws clause specifies that method quotient may throw an ArithmeticException Outline

  15. Call method quotient, which may throw ArithmeticException Exception parameters

  16. Exception Inheritance Hierarchy • Exception classes form an extensible inheritance hierarchy • Throwable objects can be used with exception mechanism • Subclass Exception: exception situations that can occur and be caught in a Java program • Subclass Error: abnormal situations happen in JVM –usually impossible for a program to recover from Errors

  17. Java Exception Hierarchy • catch block catches all exceptions of its type and subclasses of its type • An subclass exception object is a superclass exception object • If there are multiple catch blocks that match a particular exception type, only first matching catch block executes • Define a catch block for a superclass when all catch blocks for that class’s subclasses perform same functionality • This guarantees that exceptions of all subclasses will be caught. • If some subclass exceptions need special handling, position their catch blocks before the catch block for superclass type • Placing them in opposite order prevents subclass catch blocks from executing, so a compilation error occurs.

  18. Checked and Unchecked Exceptions • Checked exception, inherit from Exception but not from RuntimeException • Unchecked exception: inherit from ErrororuntimeException

  19. Checked and Unchecked Exceptions • Checked exception, inherit from Exception but not from RuntimeException • Compiler enforces a catch-or-declare requirement, i.e., someone must handle it • For each method call: • If the method declaration suggests that it throws some checked exceptions, compiler ensures that the checked exception is caught or is declared in a throws clause. • Unchecked exception: compiler does not check whether such exception is caught or declared • If it occurs and is not caught, program terminates or runs with unexpected results • Handling them makes program more robust, • e.g., NumberFormatException, a subclass of RuntimeException

  20. throws Clause in method head • throws clause – specifies exceptions a method may throws • after method’s parameter list and before method’s body • a comma-separated list of exceptions • Exceptions can be thrown by statements in method’s body of by methods called in method’s body • Exceptions can be of types listed in throws clause or subclasses • If a method explicitly throws a checked exception, or calls another method that throws one, it must list the exception in the throw clause, or catch it • If an exception can be handled meaningfully in a method, the method should catch it rather than declare it.

  21. Throwing Exceptions • You can thrown exceptions from a method if something has gone wrong • throw statement:throw followed by an exception object • Example: • Exceptions can be thrown from constructors. When an error is detected in a constructor, an exception should be thrown rather than creating an improperly formed object. • Exceptions are rethrown when a catch block decides either that it cannot process the exception or that it can only partially process it • Exception is deferred to outer try statement • Exception is rethrown by using keyword throw followed by a reference to the exception object

  22. Examples about throwing/handling exception

  23. Call method that throws an exception

  24. Create new Exception and throw it Throw previously created Exception finally block executes even though exception is rethrown in catch block

  25. finally block executes even though no exception is thrown

  26. Stack Unwinding • Stack unwinding – when an exception is thrown but not caught, method-call stack is “unwound,” and an attempt is made to catch the exception in the next outer try block. • The method in which exception was not caught terminates • All local variables in that method go out of scope • Control returns to the statement that originally invoked the method – if a try block encloses the method call, an attempt is made to catch the exception.

  27. Call method that throws an exception Catch exception that may occur in the above try block, including the call to method throwException Outline

  28. Method throws exception Throw new exception; Exception not caught in current try block, so handled in outer try block Outline finally block executes before control returns to outer try block

  29. printStackTrace, getStackTrace and getMessage • class Throwable provides method to retrieve info. about an exception • getMessage – returns the descriptive string stored in an exception • printStackTrace – outputs stack trace to standard error stream • getStackTrace – retrieves stack trace information as an array of StackTraceElement objects; enables custom processing of the exception information

  30. Exercises • Modify previous program to print out info. about Exception • what if we do not catch exception in main ? • An exception that is not caught in an application causes Java’s default exception handler to run. This displays the name of the exception, a descriptive message that indicates the problem that occurred and a complete execution stack trace. • Never ignore an exception you catch. At least use printStackTrace to output an error message. This will inform users that a problem exists, so that they can take appropriate actions.

  31. printStackTrace, getStackTrace and getMessage • StackTraceElement methods • getClassName • getFileName • getLineNumber • getMethodName • Stack trace information follows pattern – className.methodName(fileName:lineNumber)

  32. Retrieve stack information as an array of StackTraceElement objects Display stack trace for exception thrown in method3

  33. Outline

  34. Exception created and thrown Outline

  35. Chained Exceptions • Chained exceptions enable an exception object to maintain the complete stack-trace information when an exception is thrown from a catch block • Users can retrieve information about original exception • Stack trace from a chained exception displays how many chained exceptions remain

  36. Catch exception from method1 as well as any associated chained exceptions Outline

  37. Catch exception from method2, throw new exception to be chained with earlier exceptions Catch exception from method3, throw new exception to be chained with earlier exceptions Outline

  38. Original thrown exception Outline

  39. Error-Prevention Tip • Read online API documentation for a method before using that method in a program. The documentation specifies the exceptions thrown by the method (if any) and indicates reasons why such exceptions may occur. Then provide for handling those exceptions in your program. • If you know that a method might throw an exception, include appropriate exception-handling code in your program to make it more robust.

  40. Define new exception class

  41. Declaring New Exception Types • You can declare your own exception classes that are specific to the problems that can occur when another program uses your reusable classes • By convention, all exception-class names should end with word Exception. • New exception class must extend an existing exception class • Typically contains only two constructors • One takes no arguments, passes a default exception messages to the superclass constructor • One that receives a customized exception message as a string and passes it to the superclass constructor • If possible, indicate exceptions from your methods by using existing exception classes, rather than creating new exception classes. The Java API contains many exception classes that might be suitable for the type of problem your method needs to indicate.

  42. Checked or unchecked exception? • a checked exception (i.e., extend Exception but not RuntimeException) if clients should be required to handle the exception. • The client application should be able to reasonably recover from such an exception. • extend RuntimeException if the client code should be able to ignore the exception (i.e., an unchecked exception).

More Related