Lecture 15 Exception Handling
Lecture 15 Exception Handling
Exception Handling
Errors and Exceptions
The objectives of this chapter are:
1 import java.util.Scanner;
2
3 public class ExceptionDemo {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 System.out.print("Enter an integer: ");
7 int number = scanner.nextInt();
8 If an exception occurs on this
9 line, the rest of the lines in the // Display the result
method are skipped and the System.out.println(
10
program is terminated.
11 "The number entered is " + number);
12 }
13 }
Terminated.
Catch Runtime Errors
1 import java.util.*;
2
3 public class HandleExceptionDemo {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 boolean continueInput = true;
7
8 do {
9 try {
10 System.out.print("Enter an integer: ");
11 int number = scanner.nextInt();
12 If an exception occurs on this line,
13 the rest of lines in the try block are // Display the result
14 skipped and the control is System.out.println(
15 transferred to the catch block. "The number entered is " + number);
16
17 continueInput = false;
18 }
19 catch (InputMismatchException ex) {
20 System.out.println("Try again. (" +
21 "Incorrect input: an integer is required)");
22 scanner.nextLine(); // discard input
23 }
24 } while (continueInput);
25 }
13 }
Approaches to handling an exception
1. Prevent the exception from happening.
2. Catch it in the method in which it occurs, and either
a. Fix up the problem and resume normal execution.
b. Rethrow it.
c. Throw a different exception.
3. Declare that the method throws the exception.
4. With 1. and 2.a. the caller never knows there was an
error.
5. With 2.b., 2.c., and 3., if the caller does not handle the
exception, the program will terminate and display a
stack trace.
Exceptions -Syntax
try
{
// Code which might throw an exception
// ...
}
catch(FileNotFoundException x)
{
// code to handle a FileNotFound exception
}
catch(IOException x)
{
// code to handle any other I/O exceptions
}
catch(Exception x)
{
// Code to catch any other type of exception
}
finally
{
// This code is ALWAYS executed whether an exception was thrown
// or not. A good place to put clean-up code. ie. close
// any open files, etc...
}
Execution of try catch blocks
• For normal execution:
• try block executes, then finally block executes, then other
statements execute
• When an error is caught and the catch block throws an exception
or returns:
• try block is interrupted
• catch block executes (until throw or return statement)
• finally block executes
• When error is caught and catch block doesn’t throw an exception
or return:
• try block is interrupted
• catch block executes
• finally block executes
• other statements execute
• When an error occurs that is not caught:
• try block is interrupted
• finally block executes
Sequence of Events for throw
Preceding step
try block
throw
statement
unmatched catch
matching catch
unmatched catch
next step
Sequence of Events for No throw
Preceding step
try block
throw
statement
unmatched catch
matching catch
unmatched catch
next step
Sequence of Events for finally clause
Preceding step
try block
throw
statement
unmatched catch
matching catch
unmatched catch
finally
next step
Exception Handler
Exception
"thrown" here
Thrown
Thrownexception
exceptionmatched
matchedagainst
against
first
firstset
setofofexception
exceptionhandlers
handlers
Exception
handler
IfIfititfails
failsto
tomatch,
match,ititisismatched
matchedagainst
against
next
nextset
setofofhandlers,
handlers,etc.
etc.
Exception
handler
IfIfexception
exceptionmatches
matchesnone
noneofofhandlers,
handlers,
program
programisisabandoned
abandoned
Trace a Program Execution
Suppose no
exceptions in the
statements
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Trace a Program Execution
Next statement;
Trace a Program Execution
Next statement;
Trace a Program Execution
Next statement;
Trace a Program Execution
Next statement;
Trace a Program Execution
Next statement;
Trace a Program Execution
Next statement;
Trace a Program Execution
try {
statement1; statement2 throws an
statement2; exception of type
statement3; Exception2.
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
Trace a Program Execution
try {
statement1; Handling exception
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
Trace a Program Execution
try {
statement1; Rethrow the exception
statement2; and control is
statement3; transferred to the caller
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
Trace a Program Execution
try {
statement1; Execute the final block
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
Declaring, Throwing, and Catching
Exceptions
OtherException
Automatically Passing Exceptions
If your method is defined to throw an exception, you need not
catch it within your method
}
Using throws clause
If you don’t want the exception to be handled in the same function you can use the
throws class to handle the exception in the calling function.
public class myexception{
public static void main(String args[])
{ In this example, the main
try{ method calls the
checkEx(); checkEx() method and the
} catch(FileNotFoundException ex){ } checkEx method tries to
open a file, If the file in not
} available, then an
public void checkEx() throws FileNotFoundException exception is raised and
{ passed to the main
File f = new File(“myfile”); method, where it is
handled.
FileInputStream fis = new
FileInputStream(f);
//continue processing here.
}
}
Exceptions -throwing multiple exceptions
A Method can throw multiple exceptions.
Multiple exceptions are separated by commas after the throws
keyword: public class MyClass
{
public int computeFileSize() throws IOException, ArithmeticException
[...]
if (anAmount>balance)
throw new InsuffientFundsException("Not enough cash");
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
VirtualMachineError
Error
AWTError
IOException
ArithmeticException
System errors Exception areAWTException
thrown by JVM and represented in
the Error class. The ErrorNullPointerException class describes internal
RuntimeException
system errors. Such errors rarely occur. If one does,
IndexOutOfBoundsException
Object there
Throwable is little you Several
canmoredo classes beyond notifying the user and
IllegalArgumentException
trying to terminate the program gracefully.
LinkageError Several more classes
VirtualMachineError
Error
AWTError
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
VirtualMachineError
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
VirtualMachineError
RuntimeException
Error is caused by programming errors,
such as bad AWTError
casting, accessing an out-of-bounds array,
and numericSeveral
errors.
more classes
Checked Exceptions vs. Unchecked
Exceptions
(a) (b)
Unchecked Exceptions
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
VirtualMachineError
Error
AWTError Unchecked
exception.
Several more classes
Cautions When Using Exceptions