Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exception Handling in Java Reference: COS240 Syllabus

Similar presentations


Presentation on theme: "Exception Handling in Java Reference: COS240 Syllabus"— Presentation transcript:

1 Exception Handling in Java Reference: COS240 Syllabus
COS240 O-O Languages AUBG, COS dept Lecture 12 Title: Exception Handling in Java Reference: COS240 Syllabus

2 Lecture Contents: Part 1 Brief introduction to EH Part 2 Comprehensive introduction to EH

3 Part 1 Brief Intro to Exception Handling
Exceptions An exception is an event that disrupts normal program flow.

4 Three approaches to error checking
Ignore all but the most important errors. The code is cleaner, but the program will misbehave when it encounters an unusual error. Do something appropriate for every error. The code is cluttered, but the program works better. You might still forget some error conditions. 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.

5 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.

6 The list of methods is known as the call stack
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.

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

8 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.

9 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 }

10 Example try { result = numerator / denominator; validResult = true; } catch (ArithmeticException e) validResult = false;

11 try { do the “normal” code, ignoring possible exceptions }
catch (some exception) { handle the exception } finally { ... }

12 System.out.println(e.getMessage());
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 What is the “dangerous code”? Any code involving one or more methods that throw exceptions. 12

13 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 Note that one catch is more general than the other. Also note that the more specific one here will override the more general one THE ORDER MATTERS HERE! 13

14 Part 2 Exception Handling in Details

15 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.

16 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.

17 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.

18 Exception-Handling Overview
Pure, naked, risky assignment statement quotient = dividend / divisor;

19 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)

20 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 ");

21 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)

22 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"); }

23 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)

24 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"); }

25 Exception-Handling Overview
Show runtime error Quotient Fix it using an if statement or using try … catch QuotientWithIf QuotientWithException What if the runtime error occurs in a called method? See next slide QuotientWithMethod

26 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.

27 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() ); }

28 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() ); }

29 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.

30 Handling FileNotFoundException
FileNotFoundExceptionDemo Open DemoFileNotFoundException.java that raises an exception in case of file not found.

31

32 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.

33 Exception Types

34 System Errors 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.

35 Exceptions Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.

36 Runtime Exceptions RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.

37 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.

38 Unchecked Exceptions Unchecked exception.

39 Declaring, Throwing, and Catching Exceptions
Java’s EH model is based on three operations: declaring an exception throwing an exception catching an exception

40 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

41 Throwing Exceptions throw new TheException();
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;

42 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"); }

43 Catching Exceptions try {// Statements that may throw exceptions
When an exception is thrown, it can be caught and handled in a try-catch 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;

44 Catching Exceptions pp465

45 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).

46 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

47 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

48 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

49 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() } // end of class

50 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

51 Rethrowing Exceptions
try { statements; } catch(TheException ex) { // perform operations before exits; throw ex;

52 The finally Clause try { statements; } catch(TheException ex) {
handling ex; finally { finalStatements;

53 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.

54 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.

55 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");

56 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");

57 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.

58 Declaring Assertions assert assertion; or
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.

59 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.

60 Executing Assertions Example
To demonstrate effect of using assert keyword in Java: Open AssertionDemo.java source file. Compile and run the demo program.

61 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 ..."); } }

62 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.

63 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

64 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.

65 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 in Circle.java in Listing 13.8. public void setRadius(double newRadius) { assert newRadius >= 0; radius = newRadius; }

66 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.

67 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 }

68 Thank You for Your attention!
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved


Download ppt "Exception Handling in Java Reference: COS240 Syllabus"

Similar presentations


Ads by Google