Download presentation
Presentation is loading. Please wait.
1
STIA1123 : Programming 2 Exception Handling
2
Objectives Improve the reliability of code by incorporating exception-handling. Implement the try-catch blocks for catching and handling exceptions. Write methods that propagate exceptions. Distinguish the checked and unchecked exceptions.
3
Definition An exception represents an error condition that can occur during the normal course of program execution. Examples Division by zero Trying to open an input file that does not exist An array index that goes out of bounds We can increase our programs’ reliability and robustness if we catch the exceptions ourselves using error recovery routines we develop. One way to do this is to wrap the statements that may throw an exception with the try-catch control statement.
4
Java’s Mechanism of Exception Handling
A Java exception is an object that describes an exceptional (error) condition has occurred in a piece of code. When an exceptional condition occur, an object representing that exception is created and thrown in the method that caused the error. The exception-handling codes can then be executed to catch & handle the exception object; we say the thrown exception object is caught. The normal sequence of flow is terminated if the exception object is thrown and not caught.
5
Exception thrown (not caught)
//somewhere in method main() Scanner scan = new Scanner(System.in); int num = 0; System.out.print(“Enter an integer>”); num = scan.nextInt(); System.out.println(“The number you entered is “ +num); Error (stack trace) message for invalid input Enter an integer> three Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at ExceptionTest.main(ExceptionTest.java:11) Consider the given example. What would happen if the user enters a value such as the text 'ten' instead of 10? The parseInt method cannot convert such an input to an internal numerical format. This type of error is called an exception, and it will result in displaying an error message such as the one shown here. We say the parseInt method has thrown a NumberFormatException.
6
Java’s Mechanism of Exception Handling
(From the example) The execution of main() stops because once an exception has been thrown, it must be caught by an exception handler and dealt with immediately. If we have no exception handlers of our own, the exception is caught the Java run-time system. The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program.
7
Java’s Mechanism of Exception Handling (continued)
Java provides a number of exception classes to effectively represent certain common exceptions such as division by zero, invalid input, and file not found Example: When a Scanner object is used to input data into a program, any invalid input errors are handled using the class InputMismatchException When a division by zero exception occurs, the program creates an object of the class ArithmeticException
8
Exception Types All types of thrown exception objects are instances of the Throwable class or its subclasses. Throwable is at the top of the exception class hierarchy. Immediately below Throwable are two subclasses, Error & Exception) that partition exceptions into two distinct branches. Serious errors are represented by instances of the Error class or its subclasses (Note: we don’t deal with Error type, because these are typically created in response to catastrophic failures that cannot usually be handled by your program.). Exceptional cases that common applications should handle are represented by instances of the Exception class or its subclasses.
9
Throwable Hierarchy There are over 60 classes in the hierarchy.
The classes shown here are some of the more common classes in the Throwable class hierarchy. We will be seeing most of the Exception and its subclasses shown here in the later modules.
10
Java’s Mechanism of Exception Handling (continued)
Java provides a number of exception classes to effectively represent certain common exceptions such as division by zero, invalid input, and file not found Example: When a Scanner object is used to input data into a program, any invalid input errors are handled using the class InputMismatchException When a division by zero exception occurs, the program creates an object of the class ArithmeticException
11
Java’s Mechanism of Exception Handling (continued)
Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
12
Use try{} and catch{} block
Catching an Exception Use try{} and catch{} block To catch an exception: Put code that might throw an exception inside a try{} block. Put code that handles the exception inside a catch{} block. try { // statements, some of which might // throw an exception } catch ( SomeExceptionType ex ) { // statements to handle this // type of exception This example shows a way to handle a thrown exception in our code, instead of letting the system handle it, as in the previous example. If any statement inside the try block throws an exception, then the statements in the matching catch block are executed. And the program continues the execution from the statement that follows this try-catch statement.
13
Catching an Exception try catch Scanner scan = new Scanner(System.in);
int num = 0; try { System.out.print(“Enter an integer>”); num = scan.nextInt(); } catch (InputMismatchException e){ System.out.println(“Invalid input! Please enter digits only"); } System.out.println(“The number you entered is “ +num); try catch This example shows a way to handle a thrown exception in our code, instead of letting the system handle it, as in the previous example. If any statement inside the try block throws an exception, then the statements in the matching catch block are executed. And the program continues the execution from the statement that follows this try-catch statement.
14
try-catch Control Flow
This illustrates how the control flows when there is an exception and when there is no exception. In the case when no statements in the try block throw an exception, then the catch block is skipped and execution continues with the next statement following the try-catch statement. If any one of the statements throws an exception, the statements in the catch block are executed. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.
15
Getting Information There are two methods we can call to get information about the thrown exception: getMessage printStackTrace try { . . . } catch (NumberFormatException e){ System.out.println(e.getMessage()); System.out.println(e.printStackTrace()); } In the previous example, we simply displayed a fixed error message. We can get display a more generic error message by using the getMessage or printStrackTrace methods. We will experiment with these methods in the lab.
16
Multiple catch Blocks A single try-catch statement can include multiple catch blocks, one for each type of exception. try { . . . age = Integer.parseInt(inputStr); val = cal.get(id); } catch (NumberFormatException e){ } catch (ArrayIndexOutOfBoundsException e){ } In this example, we see two statements in the try block that can potentially throw exceptions. The parseInt method throws a NumberFormatException while the get method throws an ArrayIndexOutOfBoundsException when the argument id is outside the range of valid values.
17
Multiple catch Control Flow
Here's how the control flows when there are multiple catch blocks. In the case when no statements in the try block throw an exception, then all catch blocks are skipped and execution continues with the next statement following the try-catch statement. If any one of the statements throws an exception, the statements in the matching catch block are executed. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block. -Only one catch{} block gets control (the first block that matches the type of the exception ). -If no catch{} block matches the exception, none is picked (just as if there were no try{} block.)
18
Multiple catch Control Flow
The most specific exception types should appear first in the structure, followed by the more general exception types. A child class should appear before any of its ancestors. If class A is not an ancestor or descendant of class B, then it doesn't matter which appears first. Eg. the following is wrong: try { ... } catch (Exception ex ) { . . . } catch (ArithmeticException ex ) { } Here's how the control flows when there are multiple catch blocks. In the case when no statements in the try block throw an exception, then all catch blocks are skipped and execution continues with the next statement following the try-catch statement. If any one of the statements throws an exception, the statements in the matching catch block are executed. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.
19
Multiple catch Control Flow
Question: Is this ok?: try { ... } catch (NumberFormatException ex ) { . . . } catch (ArithmeticException ex ) { } Here's how the control flows when there are multiple catch blocks. In the case when no statements in the try block throw an exception, then all catch blocks are skipped and execution continues with the next statement following the try-catch statement. If any one of the statements throws an exception, the statements in the matching catch block are executed. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.
20
The finally Block There are situations where we need to take certain actions regardless of whether an exception is thrown or not. We place statements that must be executed regardless of exceptions in the finally block. try { // statements, some of which might // throw an exception } catch ( SomeExceptionType ex ) { // statements to handle this // type of exception } catch ( AnotherExceptionType ex ) { } finally { // statements which will execute no matter // how the try block was exited. } The finally block is not used often in introductory level programs, but we will introduce them here for the sake of complete coverage of the topic. For example, suppose we open a communication channel from our Java program to a remote web server to exchange data. If the data exchange is successfully completed in the try block, then we close the communication channel and finish the operation. If the data exchange is interrupted for some reason, an exception is thrown and the operation is aborted. In this case also, we need to close the communication channel, because leaving the channel open by one application blocks other applications from using it. The code to close the communication channel should therefore be placed in the finally block.
21
try-catch-finally Control Flow
Here's how the control flows when there are multiple catch blocks and the finally block. In the case when no statements in the try block throw an exception, then all catch blocks are skipped, but the statements in the finally block are executed. Execution continues with the next statement following the try-catch statement. If any one of the statements throws an exception, the statements in the matching catch block are executed first and the statements in the finally block are executed next. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.
22
Propagating Exceptions
Instead of catching a thrown exception by using the try-catch statement, we can propagate the thrown exception back to the caller of our method. The method header includes the reserved word throws. public int getAge( ) throws InputMismatchException { . . . int age = scan.nextInt(); return age; } Using the try-catch statement is the first way to handle the exceptions. The second way is to propagate the thrown exception back to the caller of the method. The method that includes the statement that calls our method must either catch it or propagate it back to their caller.
23
Throwing Exceptions We can write a method that throws an exception directly, i.e., this method is the origin of the exception. Use the throw reserved to create a new instance of the Exception or its subclasses. The method header includes the reserved word throws. public void doWork(int num) throws Exception { . . . if (num != val) throw new Exception("Invalid val"); } It is possible to throw an exception from our own method.
24
Every exception thrower must be one of two types:
When a method may throw an exception, either directly or indirectly, we call the method an exception thrower. Every exception thrower must be one of two types: catcher. propagator. We say a method throws an exception directly when the method includes the throw statement. Otherwise, a method is throwing an exception indirectly.
25
Types of Exception Throwers
An exception catcher is an exception thrower that includes a matching catch block for the thrown exception. An exception propagator does not contain a matching catch block. Note: A method may be a catcher of one exception and a propagator of another.
26
Sample Call Sequence This illustration shows a sequence of method calls among the exception throwers. Method D throws an instance of Exception. The green arrows indicate the direction of calls. The red arrows show the reversing of call sequence, looking for a matching catcher. Method B is the catcher. The call sequence is traced by using a stack.
27
Checked vs. Unchecked Exception
There are two types of exceptions: Checked. Unchecked. A checked exception is an exception that is checked at compile time, so it must be handled. An unchecked exception is not checked at compile time, so no need to handle (optional). unchecked exception include Error and RuntimeException and their subclasses. checked exception include Exception and its subclasses.
28
Checked vs. Unchecked Exception
29
Different Handling Rules
When calling a method that can throw checked exceptions use the try-catch statement and place the call in the try block, or (handle the exception) OR modify the method header to include the appropriate throws clause. (declare the exception) When calling a method that can throw unchecked exceptions, it is optional to use the try-catch statement or modify the method header to include a throws clause.
30
Handling Checked Exceptions
Callers of a method that can throw a checked exception must include the try-catch statement in the method body or the throws clause in the header.
31
Handling Runtime Exceptions
It is optional for callers of a method that can throw runtime exceptions to include the try-catch statement in the method body or the throws clause in the header.
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.