slide3.2_2009 - Module 3.2 Exceptions and Assertions...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Module 3.2 Exceptions and Assertions EE3206/EE5805 Java Programming & Applications 1 Intended Learning Outcomes To know what is exception and what is exception handling. To To distinguish exception types: Error (fatal) vs. Exception (non-fatal), and Error (fatal) Exception fatal), checked vs. uncheck exceptions. To declare exceptions in the method header. To To throw exceptions out of a method. To To write a try-catch block to handle exceptions. try To explain how an exception is propagated. To To rethrow exceptions in a try-catch block. rethrow exceptions try To use the finally clause in a try-catch block. finally clause try To know when to use exceptions. To To declare custom exception classes. To To apply assertions to help ensure program correctness. To EE3206/EE5805 Java Programming & Applications 2 Syntax Errors, Runtime Errors, and Syntax Logic Errors Logic You learned that there are three categories of errors: You Syntax errors arise because the rules of the language have not been Syntax arise followed. They are detected by the compiler. Runtime errors occur while the program is running if the environment Runtime occur detects an operation that is impossible to carry out. Logic errors occur when a program doesn't perform the way it was Logic occur intended to. EE3206/EE5805 Java Programming & Applications 3 Exceptions Handling The basic philosophy of Java is that badly formed code will not be run. The ideal time to catch an error is at compile time, before at before you even try to run the program. However, not all errors can be detected at compile time. The rest However, of the problems must be handled at runtime through some at through formality that allows the originator of the error to pass appropriate information to a recipient who will know how to appropriate who handle the difficulty properly. Java provides a neat mechanism, exception handling, as the formal way to exception as handle errors In general, reading, writing, and debugging becomes easier with exceptions handling EE3206/EE5805 Java Programming & Applications 4 Exception Types and Classes ClassNotFoundException Non-fatal exception type Exception IOException ArithmeticException AWTException NullPointerException RuntimeException IndexOutOfBoundsException Object Throwable Several more classes IllegalArgumentException LinkageError Several more classes VirtualMachineError Error AWTError Fatal exception type Several more classes EE3206/EE5805 Java Programming & Applications 5 System Errors (fatal) System 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. Exception ClassNotFoundException IOException ArithmeticException AWTException NullPointerException RuntimeException IndexOutOfBoundsException Object Throwable Several more classes IllegalArgumentException LinkageError Several more classes VirtualMachineError Error AWTError Several more classes EE3206/EE5805 Java Programming & Applications 6 Exceptions (non-fatal) Exceptions Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program. ClassNotFoundException IOException ArithmeticException Exception AWTException NullPointerException RuntimeException IndexOutOfBoundsException Object Throwable Several more classes IllegalArgumentException LinkageError Several more classes VirtualMachineError Error AWTError Several more classes EE3206/EE5805 Java Programming & Applications 7 Runtime Exceptions RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors. Exception ClassNotFoundException IOException ArithmeticException AWTException NullPointerException RuntimeException IndexOutOfBoundsException Object Throwable Several more classes IllegalArgumentException LinkageError Several more classes VirtualMachineError Error AWTError Several more classes EE3206/EE5805 Java Programming & Applications 8 Checked/Unchecked Exceptions Checked/Unchecked ClassNotFoundException IOException ArithmeticException Exception AWTException NullPointerException RuntimeException IndexOutOfBoundsException Object Throwable Several more classes IllegalArgumentException LinkageError Several more classes VirtualMachineError Error AWTError Unchecked exceptions Several more classes EE3206/EE5805 Java Programming & Applications 9 Checked/Unchecked Exceptions Unchecked Exception RuntimeException, Error and their subclasses are known as unchecked exceptions. Programmer is not forced to catch them. In most cases, unchecked exceptions reflect programming logic errors that are not recoverable. For example, a NullPointerException is thrown if you access an object through a reference variable before an object is assigned to it; an IndexOutOfBoundsException is thrown if you access an element in an array outside the bounds of the array. These are the logic errors that should be corrected in the program code. Checked Exception All other exceptions are known as checked exceptions. The compiler forces the programmer to check and deal with the exceptions. EE3206/EE5805 Java Programming & Applications 10 Exception Handling Exception Handling involves three parts: Exception Declaring Throwing Throwing Catching Catching Pseudo code method1() { method2() throws Exception { try { invoke method2; } catch (Exception ex) { Process exception; } } if (an error occurs) { throw new Exception(); } } declare exception catch exception throw exception EE3206/EE5805 Java Programming & Applications 11 Declaring Exceptions Every method must state the types of checked exceptions it Every might throw. This is known as declaring exceptions. declaring Examples: Examples: public void myMethod() throws IOException { // may throw IOException here } public void myMethod() throws IOException, ClassNotFoundException { // may throw two types of exception here } EE3206/EE5805 Java Programming & Applications 12 Throwing Exceptions When the program detects an error, the program can create an When instance of an appropriate exception type and throw it. This is instance and known as throwing an exception. Here are two examples: throwing Here throw new Exception(); Exception ex = new Exception(); Exception throw ex; /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException("Radius cannot be negative"); } EE3206/EE5805 Java Programming & Applications 13 Catching Exceptions try { /* Statements that may throw exceptions that are * instances of Exception1, Exception2, … ExceptionN */ statements; statements; statements; statements; } catch (Exception1 exVar1) { handler for exception1; } catch (Exception2 exVar2) { handler for exception2; } ... catch (ExceptionN exVar3) { handler for exceptionN; } EE3206/EE5805 Java Programming & Applications 14 Catch or Declare Checked Exceptions Java forces you to deal with checked exceptions. If a method decllares a checked ares Java exception (i.e., an exception other than Error or RuntimeException), you must Error or RuntimeException), invoke it in a try-catch block or declare to throw the exception in the calling try or declare the method. For example, suppose that method p1 iinvokes method p2 and p2 may throw a p1 nvokes p2 and p2 may checked exception (e.g., IOException), you have to write the code as shown in (a) IOException), or (b). or Handle the exception locally, i.e. resolved by p1( ) v oid p1() { t ry { p 2(); } c atch (IOException ex) { ... } } ( a) Forward the exception to the caller of p1( ) v oid p1() t hrows IOException { p 2(); } ( b) EE3206/EE5805 Java Programming & Applications 15 Without Catching Runtime Errors 1 2 3 4 5 6 7 8 9 10 11 12 13 import java.util.Scanner; public class ExceptionDemo { public static void main(String args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer: "); int number = scanner.nextInt(); If an exception occurs on this line, the rest of the lines in the method are skipped and the program is terminated. // Display the result System.out.println( "The number entered is " + number); } } Terminated. Run EE3206/EE5805 Java Programming & Applications 16 Catching Runtime Errors 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 import java.util.*; public class HandleExceptionDemo { public static void main(String args) { Scanner scanner = new Scanner(System.in); boolean continueInput = true; do { try { System.out.print("Enter an integer: "); int number = scanner.nextInt(); If an exception occurs on this line, the rest of lines in the try block are skipped and the control is transferred to the catch block. Run // Display the result System.out.println( "The number entered is " + number); continueInput = false; } catch (InputMismatchException ex) { System.out.println("Try again. (" + "Incorrect input: an integer is required)"); scanner.nextLine(); // discard input } } while (continueInput); } } EE3206/EE5805 Java Programming & Applications 17 Example: Declaring, Throwing, Example: and Catching Exceptions and Objective: This example demonstrates declaring, throwing, and catching exceptions by modifying the setRadius method setRadius method in the Circle class. The new setRadius method throws an Circle class. setRadius method exception if radius is negative. exception TestCircleWithException Run CircleWithException EE3206/EE5805 Java Programming & Applications 18 Rethrowing Exceptions Sometimes you may want to re-throw the exception that you just caught, particularly Sometimes throw when you want the exception to be processed by multiple handlers. In this case, you when In can simply throw the exception instance again. can Re-throwing an exception immediately causes a jump to the exception handlers in the Re handlers upper context. Any further catch clauses for the same try block are ignored. catch clauses try block try { statements; statements; } catch(Exception1 ex) catch(Exception1 perform operations perform throw ex; } catch(Exception2 ex) catch(Exception2 perform operations perform } { before exits; Re-throw the instance ex { before exits; EE3206/EE5805 Java Programming & Applications 19 Performing Cleanup with finally Performing finally There’s often some piece of code that you want to execute whether or not an There ot exception is thrown within a try block. To achieve this effect, you use a finally clause at the end of all the exception handlers. If any catch block re-throws the exception, the finally block will be executed If throws before the exception handling control passed to the upper handler. before try { try // The guarded region: Dangerous activities // that might throw A, B, or C } catch(A a1) { a1) // Handler for situation A } catch(B b1) { b1) // Handler for situation B } catch(C c1) { catch(C c1) // Handler for situation C } finally { // Activities that happen every time } cleanup the try-catch block EE3206/EE5805 Java Programming & Applications 20 animation Trace a Program Execution Suppose no exceptions in the statements try { try statements; statements; } catch(TheException ex) { ex) handling ex; } finally { finally finalStatements; finalStatements } Next statement; EE3206/EE5805 Java Programming & Applications 21 animation Trace a Program Execution try { try statements; statements; } catch(TheException ex) { ex) handling ex; } finally { finally finalStatements; finalStatements } Next statement; EE3206/EE5805 Java Programming & Applications 22 The final block is always executed animation Trace a Program Execution try { try statements; statements; } catch(TheException ex) { ex) handling ex; } finally { finally finalStatements; finalStatements } Next statement; EE3206/EE5805 Java Programming & Applications 23 Next statement in the method is executed animation Trace a Program Execution try { try statement1; statement1; statement2; statement3; } catch(Exception1 ex) { catch(Exception1 handling ex; } finally { finally finalStatements; finalStatements } Next statement; Suppose an exception of type Exception1 is thrown in statement2 EE3206/EE5805 Java Programming & Applications 24 animation Trace a Program Execution try { try statement1; statement1; statement2; statement3; } catch(Exception1 ex) { catch(Exception1 handling ex; } finally { finally finalStatements; finalStatements } Next statement; The exception is handled. EE3206/EE5805 Java Programming & Applications 25 animation Trace a Program Execution try { try statement1; statement1; statement2; statement3; } catch(Exception1 ex) { catch(Exception1 handling ex; } finally { finally finalStatements; finalStatements } Next statement; The final block is always executed. EE3206/EE5805 Java Programming & Applications 26 animation Trace a Program Execution try { try statement1; statement1; statement2; statement3; } catch(Exception1 ex) { catch(Exception1 handling ex; } finally { finally finalStatements; finalStatements } Next statement; The next statement in the method is now executed. EE3206/EE5805 Java Programming & Applications 27 animation Trace a Program Execution try { try statement1; statement1; statement2; statement3; } catch(Exception1 ex) { catch(Exception1 handling ex; } catch(Exception2 ex) { catch(Exception2 handling ex; throw ex; throw } finally { finally finalStatements; finalStatements } Next statement; statement2 throws an exception of type Exception2. EE3206/EE5805 Java Programming & Applications 28 animation Trace a Program Execution try { try statement1; statement1; statement2; statement3; } catch(Exception1 ex) { catch(Exception1 handling ex; } catch(Exception2 ex) { catch(Exception2 handling ex; throw ex; throw } finally { finally finalStatements; finalStatements } Next statement; Handling exception EE3206/EE5805 Java Programming & Applications 29 animation Trace a Program Execution try { try statement1; statement1; statement2; statement3; } catch(Exception1 ex) { catch(Exception1 handling ex; } catch(Exception2 ex) { catch(Exception2 handling ex; throw ex; throw } finally { finally finalStatements; finalStatements } Next statement; Execute the final block EE3206/EE5805 Java Programming & Applications 30 animation Trace a Program Execution try { try statement1; statement1; statement2; statement3; } catch(Exception1 ex) { catch(Exception1 handling ex; } catch(Exception2 ex) { catch(Exception2 handling ex; throw ex; throw } finally { finally finalStatements; finalStatements } Next statement; Rethrow the exception and control is transferred to the caller *the control will not be returned and this statement will not be executed. EE3206/EE5805 Java Programming & Applications 31 Cautions When Using Exceptions Exception handling separates error-handling code from normal programming Exception handling tasks, thus making programs easier to read and to modify. Be aware, however, that exception handling usually requires more time and resources because it requires instantiating a new exception object, rolling back resources because the call stack, and propagating the errors to the calling methods. the When you detect an exception in a method, When If you can handle the exception in the method where it occurs, there is no need to If here throw exception. throw If you want the exception to be processed by its caller, you should create an If uld exception object and throw it. (This usually implies that the calller should have more ler exception information about processing this exception and could handle it better.) better.) EE3206/EE5805 Java Programming & Applications 32 When to Use Exceptions When should you use the try-catch block in the code? You should use it to deal catch with unexpected error conditions. Do not use it to deal with simple, expected unexpected Do situations. For example, the following code: try { System.out.println(refVar.toString()); } catch (NullPointerException ex) { System.out.println("refVar is null"); } is better to be replaced by this code: (more efficient) if (refVar != null) System.out.println(refVar.toString()); else System.out.println("refVar is null"); EE3206/EE5805 Java Programming & Applications 33 Assertions An assertion is a Java statement that enables you to assert an assumption about your program. Assertions is used to assure program correctness and avoid logic errors. correctness An assertion contains a Boolean expression that should be true should during program execution. during Assertions are checked at runtime and can be turned on or off at can at startup time. startup An assertion iis declared using the Java keyword assert as follows: An assertion s assert assert assertion; or assert assertion assert assertion : detailMessage; assert assertion detailMessage where assertion iis a boolean expression where assertion s boolean expression and detailMessage iis a primitive value or an instance of Object. detailMessage s EE3206/EE5805 Java Programming & Applications 34 Executing Assertions When an assertion statement is executed, Java evaluates the assertion. If When rtion. it is false, an AssertionError will be thrown. AssertionError The AssertionError class has a no-arg constructor and seven AssertionError constructor overloaded single-argument constructors of type int, llong, float, double, overloaded argument int ong, boolean, char, and Object. boolean char, For the first assert statement with no detail message, the no-arg For constructor of AssertionError iis used. constructor AssertionError s For the second assert statement with a detail message, an appropriate For riate AssertionError constructor is used to match the data type of the message. AssertionError constructor Since AssertionError iis a subclass of Error, when an assertion becomes AssertionError s false, the program displays a message on the console and exits. EE3206/EE5805 Java Programming & Applications 35 Executing Assertions Example public class AssertionDemo { public AssertionDemo public static void main(String args) { public args int i; int sum = 0; i; int for (i = 0; i < 10; i++) { sum += i; sum } assert i == 10; // assure the loop finished properly // assert sum > 10 && sum < 5 * 10 : "sum is " + sum; assert } } EE3206/EE5805 Java Programming & Applications 36 Running Programs with Assertions By default, the assertions are disabled at runtime. To enable it, use the switch – use enableassertions, or –ea for short, as follows: or java –ea AssertionDemo java ea AssertionDemo Assertions can be selectively enabled or disabled at class level or package level. The or disable switch is –disableassertions or –da for short. or for For example, the following command enables assertions in package package1 and For and disables assertions in class Class1. Class1 java –ea:package1 –da:Class1 AssertionDemo java ea:package1 da:Class1 AssertionDemo Latter parameter overrides former parameter EE3206/EE5805 Java Programming & Applications 37 Proper Use of Assertions Using assertions as a general-purpose error handling mechanism is unwise Using purpose because assertions do not allow for recovery from errors. An assertion failure will because ertion halt the program's execution abruptly. halt Use assertions to reaffirm assumptions. An assumption is a condition that is Use An supposed to be true in all situations. A common use of assertions is to replace assumptions in comments with common with assertions in the code. assertions int total = countNumberOfUsers(); if (total % 2 == 0) { // total is even } else { assert (total % 2 == 1); } int total = countNumberOfUsers(); if (total % 2 == 0) { // total is even } else { // total is odd } assert (month > 0 && month < 13); switch (month) { case 1: ... ; break; case 2: ... ; break; ... case 12: ... ; break; default: assert false : "Invalid month: " + month; } // pre-condition // post-condition 38 EE3206/EE5805 Java Programming & Applications Exception Handling vs. Assertions Both exception handling and assertions are not used for routine error testing. Exception handling deals with unusual circumstances during unusual during program execution. Assertions are to assure the correctness of the program. program Exception handling addresses robustness (recover from error) robustness (recover and assertion addresses correctness (affirm no error). correctness (affirm EE3206/EE5805 Java Programming & Applications 39 ...
View Full Document

This note was uploaded on 04/20/2010 for the course ELECTRONIC EE3206 taught by Professor Tingchiwang during the Spring '10 term at École Normale Supérieure.

Ask a homework question - tutors are online