Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exception Handling 1 CISC6795, Spring 2011. Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:

Similar presentations

Presentation on theme: "Exception Handling 1 CISC6795, Spring 2011. Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:"— Presentation transcript:

1 Exception Handling 1 CISC6795, Spring 2011

2 Introduction 2 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 3 Attempt to divide; denominator may be zero Read input; exception occurs if input is not a valid integer

4 Outline 4

5 Exception-Handling Overview 5 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 6 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 7 try statement : one try 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 Outline 8 throws clause specifies that method quotient may throw an ArithmeticException try block attempts to read input and perform division

9 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 10 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 place try... Catch… finally... around every statement that may throw an exception.

11 Catch block 11 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 12 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 13 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 Outline 14 throws clause specifies that method quotient may throw an ArithmeticException try block attempts to read input and perform division

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

16 16

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

18 Java Exception Hierarchy 18 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.

19 Checked and Unchecked Exceptions 19 Checked exception, inherit from Exception but not from RuntimeException Unchecked exception: inherit from Error or untimeException

20 Checked and Unchecked Exceptions 20 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

21 throws Clause in method head 21 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.

22 Throwing Exceptions 22 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

23 Examples about throwing/handling exception 23

24 24 Call method that throws an exception

25 25 Create new Exception and throw itThrow previously created Exceptionfinally block executes even though exception is rethrown in catch block

26 26 finally block executes even though no exception is thrown

27 Stack Unwinding 27 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.

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

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

30 printStackTrace, getStackTrace and getMessage 30 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

31 Exercises 31 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.

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

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

34 Outline 34

35 Outline 35 Exception created and thrown

36 Chained Exceptions 36 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

37 Outline 37 Catch exception from method1 as well as any associated chained exceptions

38 Outline 38 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

39 Outline 39 Original thrown exception

40 Error-Prevention Tip 40 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.

41 Define new exception class 41

42 Declaring New Exception Types 42 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.

43 Checked or unchecked exception? 43 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).

Download ppt "Exception Handling 1 CISC6795, Spring 2011. Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:"

Similar presentations

Ads by Google