Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
COS240 O-O Languages AUBG, COS dept Lecture 12 Title: Exception Handling in Java Reference: COS240 Syllabus Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 Lecture Contents: Part 1 Brief introduction to EH Part 2 Comprehensive introduction to EH Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 2 Part 1 Brief Intro to Exception Handling Exceptions An exception is an event that disrupts normal program flow. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 3 Three approaches to error checking 1. Ignore all but the most important errors. The code is cleaner, but the program will misbehave when it encounters an unusual error. 2. Do something appropriate for every error. The code is cluttered, but the program works better. You might still forget some error conditions. 3. Do the normal processing in one place, handle the errors in another (this is the Java and C# way). The code is at least reasonably uncluttered. 4 Java and C# approach: When an error occurs within a method (e.g. divide by zero; array index out of bounds; etc.), the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception. 5 After a method throws an exception, the runtime system attempts to find some code to handle it. The set of possible code to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack The call stack. 6 The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler. 7 The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, the runtime system (and, consequently, the program) terminates. 8 The try statement • Java provides a control structure, the try statement (also called the try-catch statement) to separate “normal” code from error handling: try { do the “normal” code, ignoring possible exceptions } catch (some exception) { handle the exception } catch (some other exception) { handle the exception } 9 Example try { result = numerator / denominator; validResult = true; } catch (ArithmeticException e) { validResult = false; } 10 try { do the “normal” code, ignoring possible exceptions } catch (some exception) { handle the exception } finally { ... } 11 Catching an Exception try { // normal code here! } catch(Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); // print call stack } • getMessage() is a method of the Throwable class that returns the error message describing the exception. • printStackTrace() is also a method of the Throwable class 12 Multiple catch Statements Order Matters! Less general first! try { // normal code here! } catch(ArithmeticException e) { // Specific error handling here } catch(AnotherException e) { // More general error handling here } 13 Part 2 Exception Handling in Details Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 14 Part 2 Lecture Contents: To get an overview of exceptions and exception handling. To explore the advantages of using exception handling. To distinguish exception types: Error (fatal) vs. Exception (nonfatal), and checked vs. unchecked. To declare exceptions in a method header. To throw exceptions in a method. To write a try-catch block to handle exceptions. To explain how an exception is propagated. To use the finally clause in a try-catch block. To use exceptions only for unexpected errors. To rethrow exceptions in a catch block. To create chained exceptions. To define custom exception classes. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 15 Introduction When a program runs into a runtime error, the program terminates abnormally. In Java, runtime errors are caused by exceptions. An exception is an object that represents an error or an abnormal condition. If the exception is not handled, the program will terminate abnormally. How can you handle the runtime error so that the program can continue to run or terminate gracefully? This is the Exception Handling subject. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 16 Exception-Handling Overview To demonstrate EH, including how an exception object is created and thrown: Open Quotient.java that reads two integers and displays their quotient. Run program with regular data Run program with illegal data (integer zero div) FYI: FP real value divided by zero does not raise an exception. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 17 Exception-Handling Overview Pure, naked, risky assignment statement quotient = dividend / divisor; Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 18 Exception-Handling Overview Simple way to fix the problem is to add if stmt to test the divisor: Open QuotientWithIf.java that reads two integers and displays their quotient. Run program with regular data Run program with illegal data (integer zero div) Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 19 Exception-Handling Overview User specified if statement if (divisor != 0) { quotient = dividend / divisor; System.out.println(dividend+" / "+divisor+" is = "+quotient); } else System.out.println("Divisor cannot be zero "); Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 20 Exception-Handling Overview To demonstrate EH, including how to create, throw, catch and handle an exception object: Open QuotientWithExcepionVerLiang.java that reads two integers and displays their quotient. Run program with regular data Run program with illegal data (integer zero div) Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 21 Exception-Handling Overview Explicitly written code to throw an exception try { … if (divisor == 0) throw new ArithmeticException("Divisor cannot be zero "); quotient = dividend / divisor; System.out.println(dividend + " / " + divisor + " is = " + quotient); } // end of try catch (ArithmeticException aeRef) { System.out.println(" Exception: integer cannot divide by zero "); System.out.println(aeRef.getMessage()); aeRef.printStackTrace(); // print call stack } catch (InputMismatchException imeRef) { System.out.println(" Exception " + imeRef.toString() ); } finally { System.out.println("\n\n Finally block executed"); } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 22 Exception-Handling Overview To demonstrate EH, including how to create, throw, catch and handle an exception object: Open QuotientWithExcepionVerMalik.java that reads two integers and displays their quotient. Run program with regular data Run program with illegal data (integer zero div) Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 23 Exception-Handling Overview No explicit code to throw an exception Program implicitly creates exception and throws it try { … quotient = dividend / divisor; System.out.println(dividend + " / " + divisor + " is = " + quotient); } // end of try catch (ArithmeticException aeRef) { System.out.println(" Exception: integer cannot divide by zero "); System.out.println(aeRef.getMessage()); aeRef.printStackTrace(); // print call stack } catch (InputMismatchException imeRef) { System.out.println(" Exception " + imeRef.toString() ); } finally { System.out.println("\n\n Finally block executed"); } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 24 Exception-Handling Overview Show runtime error Quotient Fix it using an if statement QuotientWithIf or using try … catch QuotientWithException What if the runtime error occurs in a called method? QuotientWithMethod See next slide Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 25 Exception-Handling Advantages To demonstrate EH advantages: Open QuotientWithMethod.java that reads two integers and displays their quotient. Run program with regular data Run program with illegal data (integer zero div) Now you see the advantages of using EH. It enables a method to throw an exception (implicitly or explicitly) to its caller. Without this capability, a method must handle the exception or terminate the program. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 26 Exception-Handling Advantages Exception explicitly raised in one method Exception caught in another method public static int quotient(int num1, int num2) throws ArithmeticException { if (num2 == 0) throw new ArithmeticException("Divisor cannot be zero "); return num1/num2; } public static void main(String[] args) { try { result = quotient(dividend, divisor); System.out.println(dividend + " / " + divisor + " is = " + result); } // end of try catch (ArithmeticException aeRef) { System.out.println(" Exception: an integer cannot be divided by zero "); System.out.println(aeRef.getMessage()); aeRef.printStackTrace(); // print call stack } catch (InputMismatchException imeRef) { System.out.println(" Exception " + imeRef.toString() ); } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 27 Exception-Handling Advantages Exception implicitly raised in one method Exception caught in another method public static int quotient(int num1, int num2) throws ArithmeticException { // if (num2 == 0) // throw new ArithmeticException("Divisor cannot be zero "); return num1/num2; } public static void main(String[] args) { try { result = quotient(dividend, divisor); System.out.println(dividend + " / " + divisor + " is = " + result); } // end of try catch (ArithmeticException aeRef) { System.out.println(" Exception: an integer cannot be divided by zero "); System.out.println(aeRef.getMessage()); aeRef.printStackTrace(); // print call stack } catch (InputMismatchException imeRef) { System.out.println(" Exception " + imeRef.toString() ); } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 28 Handling InputMismatchException InputMismatchExceptionDemo Open DemoMismatchException.java that reads correctly input stream of integers. By handling InputMismatchException, your program will continuously read an input until it is correct. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 29 Handling FileNotFoundException FileNotFoundExceptionDemo Open DemoFileNotFoundException.java that raises an exception in case of file not found. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 30 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 31 The class Throwable has two direct subclasses, Exception and Error. Exceptions (members of the Exception family) are thrown to signal abnormal conditions that can often be handled by some code, though some may not be caught. Errors (members of the Error family) are usually thrown for more serious problems, such as OutOfMemoryError, that may not be so easy to handle. In general, code you write should throw only exceptions, not errors. Errors are usually thrown by the methods of the Java API, or by the Java Virtual Machine itself. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 32 Exception Types ClassNotFoundException ArithmeticException IOException Exception NullPointerException RuntimeException IndexOutOfBoundsException Many more classes Object IllegalArgumentException Throwable Many more classes LinkageError Error VirtualMachineError Many more classes Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 33 System Errors ClassNotFoundException ArithmeticException IOException Exception NullPointerException RuntimeException IndexOutOfBoundsException Many more classes Object IllegalArgumentException Throwable 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. Many more classes LinkageError Error VirtualMachineError Many more classes Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 34 Exceptions Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program. ClassNotFoundException ArithmeticException IOException Exception NullPointerException RuntimeException IndexOutOfBoundsException Many more classes Object IllegalArgumentException Throwable Many more classes LinkageError Error VirtualMachineError Many more classes Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 35 Runtime Exceptions ClassNotFoundException ArithmeticException IOException Exception NullPointerException RuntimeException IndexOutOfBoundsException Many more classes Object IllegalArgumentException Throwable Many more classes LinkageError Error VirtualMachineError RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors. Many more classes Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 36 Checked Exceptions vs. Unchecked Exceptions RuntimeException, 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. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 37 Unchecked Exceptions ClassNotFoundException ArithmeticException IOException Exception NullPointerException RuntimeException IndexOutOfBoundsException Many more classes Object IllegalArgumentException Throwable Many more classes LinkageError Error VirtualMachineError Unchecked exception. Many more classes Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 38 Declaring, Throwing, and Catching Exceptions Java’s EH model is based on three operations: declaring an exception throwing an exception catching an exception method1() { try { invoke method2; } catch (Exception ex) { Process exception; } catch exception declare exception method2() throws Exception { if (an error occurs) { throw new Exception(); } throw exception } } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 39 Declaring Exceptions Every method must state the types of checked exceptions it might throw. This is known as declaring exceptions. public void myMethod() throws IOException public void myMethod() throws IOException, OtherException Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 40 Throwing Exceptions When the program detects an error, the program can create an instance of an appropriate exception type and throw it. This is known as throwing an exception. Here is an example, throw new TheException(); TheException ex = new TheException(); throw ex; Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 41 Throwing Exceptions Example /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 42 Catching Exceptions When an exception is thrown, it can be caught and handled in a trycatch block as follows: try {// Statements that may throw exceptions statements; } catch (Exception1 exVar1) { handler for exception1; } catch (Exception2 exVar2) { handler for exception2; } ... catch (ExceptionN exVarN) { handler for exceptionN; } 43 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 Catching Exceptions pp465 try try try catch catch catch An exception is thrown in method3 Call Stack method3 main method method2 method2 method1 method1 method1 main method main method main method Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 44 Catch or Declare Checked Exceptions Java forces you to deal with checked exceptions. If a method declares a checked exception (i.e., an exception other than Error or RuntimeException), you must invoke it in a try-catch block or declare to throw the exception in the calling method. For example, suppose that method p1 invokes method p2 and p2 may throw a checked exception (e.g., IOException), you have to write the code as shown in (a) or (b). void p1() { try { p2(); } catch (IOException ex) { ... } } (a) void p1() throws IOException { p2(); } (b) Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 45 Example: Declaring, Throwing, and Catching Exceptions Objective: This example demonstrates declaring, throwing, and catching exceptions by modifying the setRadius() method in the Circle class. The new setRadius() method throws an exception if radius is negative. Open CircleWithException.java file TestCircleWithException CircleWithException Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 46 E.g.: Declaring, Throwing, and Catching Exceptions class Circle { … // methods mutators public void setRadius(double par) throws IllegalArgumentException { if (par >= 0.0) radius = par; else throw new IllegalArgumentException("Radius cannot be negative"); } … } // end of class Circle public class CircleWithException { public static void main(String[] args) { try { Circle a = new Circle(); Circle b = new Circle(5.); Circle c = new Circle(-5.); } catch (IllegalArgumentException ex){ System.out.println("\n-->>" + ex + "\n-->>"); System.out.println("\n-->>" + ex.getMessage() + "\n-->>"); ex.printStackTrace(); // print call stack } finally { System.out.println("\n Finally block executed"); } } // end of method main() } // end of class Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 47 Defining Custom Exception Classes Use the exception classes in the API whenever possible. Define custom exception classes if the predefined classes are not sufficient. Define custom exception classes by extending Exception or a subclass of Exception. the setRadius() method throws an exception if the radius is negative. Suppose you wish to pass the radius to the handler, you have to create a custom exception class. Open CircleWithUserException.java file Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 48 Defining Custom Exception Classes class IllegalRadiusException extends Exception { private double rad; public IllegalRadiusException(double radius) { // constructor super("Invalid radius " + radius); rad = radius; } public double getRad() { return rad; } } // end of class IllegalRadiusException class Circle { // methods mutators public void setRadius(double par) throws IllegalRadiusException { if(par >= 0.0) radius = par; else throw new IllegalRadiusException(par); } } // end of class Circle public class CircleWithUserException { public static void main(String[] args) { try { Circle a = new Circle(88.); //a.setRadius(-22.); Circle b = new Circle(5.); // Circle c = new Circle(-5.); } catch (IllegalRadiusException ex){ System.out.println("\n-->>\nInvalid radius is " + ex.getRad() + "\n-->>"); } } // end of method main() Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 49 try { // normal code here! } catch(Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); // print call stack } getMessage() is a method of the Throwable class that returns the error message describing the exception. printStackTrace() is also a method of the Throwable class Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 50 Rethrowing Exceptions try { statements; } catch(TheException ex) { // perform operations before exits; throw ex; } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 51 The finally Clause try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 52 Cautions When Using Exceptions (+) Exception handling separates error-handling code from normal programming 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 the call stack, and propagating the errors to the calling methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 53 When to Throw Exceptions An exception occurs in a method. If you want the exception to be processed by its direct caller or by a method within the chain of its callers, you should create an exception object and throw it. If you can handle the exception in the method where it occurs, there is no need to throw it. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 54 When to Use Exceptions? You should use it to deal with unexpected error conditions. Do not use it to deal with simple, expected situations. For example, the following code try { System.out.println(refVar.toString()); } catch (NullPointerException ex) { System.out.println("refVar is null"); } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 55 When to Use Exceptions is better to be replaced by if (refVar != null) System.out.println(refVar.toString()); else System.out.println("refVar is null"); Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 56 Assertions An assertion is a Java statement that enables you to assert an assumption about your program. An assertion contains a Boolean expression that should be true during program execution. Assertions can be used to assure program correctness and avoid logic errors. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 57 Declaring Assertions An assertion is declared using the new Java keyword assert in JDK 1.4 as follows: assert assertion; or assert assertion : detailMessage; where assertion is a Boolean expression and detailMessage is a primitive-type or an Object value. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 58 Executing Assertions When an assertion statement is executed, Java evaluates the assertion. If it is false, an AssertionError will be thrown. The AssertionError class has a no-arg constructor and seven overloaded single-argument constructors of type int, long, float, double, boolean, char, and Object. For the first assert statement with no detail message, the no-arg constructor of AssertionError is used. For the second assert statement with a detail message, an appropriate AssertionError constructor is used to match the data type of the message. Since AssertionError is a subclass of Error, when an assertion becomes false, the program displays a message on the console and exits. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 59 Executing Assertions Example To demonstrate effect of using assert keyword in Java: Open AssertionDemo.java source file. Compile and run the demo program. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 60 Executing Assertions Example public class AssertionDemo { public static void main(String[] args) { int i; int sum = 0; for (i = 0; i <=10; i++) { sum += i; } assert i == 12; assert sum > 10 && sum < 5 * 10 : "sum is " + sum; } } System.out.println("\n\nExecution continues ..."); Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 61 Compiling Programs with Assertions Since assert is a new Java keyword introduced in JDK 1.4, you have to compile the program using a JDK 1.4 compiler. Furthermore, you need to include the switch –source 1.4 in the compiler command as follows: javac –source 1.4 AssertionDemo.java NOTE: If you use JDK 1.5, there is no need to use the –source 1.4 option in the command. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 62 Running Programs with Assertions By default, the assertions are disabled at runtime. To enable it, use the switch –enableassertions, or –ea for short, as follows: java –ea AssertionDemo Assertions can be selectively enabled or disabled at class level or package level. The disable switch is – disableassertions or –da for short. For example, the following command enables assertions in package package1 and disables assertions in class Class1. java –ea:package1 –da:Class1 AssertionDemo Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 63 Using Exception Handling or Assertions Assertion should not be used to replace exception handling. Exception handling deals with unusual circumstances during program execution. Assertions are to assure the correctness of the program. Exception handling addresses robustness and assertion addresses correctness. Like exception handling, assertions are not used for normal tests, but for internal consistency and validity checks. Assertions are checked at runtime and can be turned on or off at startup time. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 64 Using Exception Handling or Assertions, cont. Do not use assertions for argument checking in public methods. Valid arguments that may be passed to a public method are considered to be part of the method’s contract. The contract must always be obeyed whether assertions are enabled or disabled. For example, the following code should be rewritten using exception handling as shown in Lines 28-35 in Circle.java in Listing 13.8. public void setRadius(double newRadius) { assert newRadius >= 0; radius = newRadius; } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 65 Using Exception Handling or Assertions, cont. Use assertions to reaffirm assumptions. This gives you more confidence to assure correctness of the program. A common use of assertions is to replace assumptions with assertions in the code. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 66 Using Exception Handling or Assertions, cont. Another good use of assertions is place assertions in a switch statement without a default case. For example, switch (month) { case 1: ... ; break; case 2: ... ; break; ... case 12: ... ; break; default: assert false : "Invalid month: " + month } Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 67 Thank You for Your attention! Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 68