Exception Handling
JAVA FUNDAMENTAL
HILMY A. TAWAKAL 1
Chapter Goals
●
To learn how to throw exceptions
●
To be able to design your own exception classes
●
To understand the difference between checked and
unchecked exceptions
●
To learn how to catch exceptions
●
To know when and where to catch an exception
04/24/2019 HILMY A. TAWAKAL 2
Error Handling
●
Traditional approach: Method returns error code
●
Problem: Forget to check for error code
– Failure notification may go undetected
●
Problem: Calling method may not be able to do anything about
failure
– Program must fail too and let its caller worry about it
– Many method calls would need to be checked
●
Instead of programming for success
[Link]()
you would always be programming for failure:
if (![Link]()) return false;
04/24/2019 HILMY A. TAWAKAL 3
Throwing Exceptions
●
Exceptions:
– Can't be overlooked
– Sent directly to an exception handler–not just caller of failed method
●
Throw an exception object to signal an exceptional condition
● Example: IllegalArgumentException: illegal parameter value
IllegalArgumentException exception
= new IllegalArgumentException("Amount exceeds balance");
throw exception;
●
No need to store exception object in a variable:
throw new IllegalArgumentException("Amount exceeds balance");
●
When an exception is thrown, method terminates immediately
Execution continues with an exception handler
04/24/2019 HILMY A. TAWAKAL 4
Example
public class BankAccount{
public void withdraw(double amount)
{
if (amount > balance)
{
IllegalArgumentException exception
= new IllegalArgumentException("Amount exceeds balance");
throw exception;
}
balance = balance - amount;
}
. . .
}
04/24/2019 HILMY A. TAWAKAL 5
Demo
04/24/2019 HILMY A. TAWAKAL 6
Exercise
●
When depositing an amount into a bank account, we don’t
have to worry about overdrafts—except when the amount is
negative. Write a statement that throws an appropriate
exception in that case.
04/24/2019 HILMY A. TAWAKAL 7
Hierarchy of Exception Classes
04/24/2019 HILMY A. TAWAKAL 8
Hierarchy of Exception Classes
04/24/2019 HILMY A. TAWAKAL 9
Syntax : Throwing an Exception
throw exceptionObject;
●
Example:
throw new IllegalArgumentException();
●
Purpose:
To throw an exception and transfer control
to a handler for this exception type
04/24/2019 HILMY A. TAWAKAL 10
Checked and Unchecked Exceptions
Two types of exceptions:
●
Checked
– The compiler checks that you don't ignore them
– Due to external circumstances that the programmer cannot prevent
– Majority occur when dealing with input and output
– For example, IOException
●
Unchecked:
– Extend the class RuntimeException or Error
– They are the programmer's fault
– Examples of runtime exceptions:
NumberFormatException, IllegalArgumentException, NullPointerException
● Example of error: OutOfMemoryError
04/24/2019 HILMY A. TAWAKAL 11
Checked and Unchecked Exceptions
●
Categories aren't perfect:
– [Link] throws unchecked InputMismatchException
– Programmer cannot prevent users from entering incorrect input
– This choice makes the class easy to use for beginning programmers
●
Deal with checked exceptions principally when programming with files and
streams
●
For example, use a Scanner to read a file
String filename = . . .;
FileReader reader = new FileReader(filename);
Scanner in = new Scanner(reader);
●
But, FileReader constructor can throw a FileNotFoundException
04/24/2019 HILMY A. TAWAKAL 12
Checked and Unchecked Exceptions
●
Two choices:
1) Handle the exception
2) Tell compiler that you want method to be terminated when the
exception occurs
●
Better to declare exception than to handle it incompetently
04/24/2019 HILMY A. TAWAKAL 13
Checked and Unchecked Exceptions
●
Use throws specifier so method can throw a checked exception
public void read(String filename) throws FileNotFoundException
{
FileReader reader = new FileReader(filename);
Scanner in = new Scanner(reader);
. . .
}
●
For multiple exceptions:
public void read(String filename)
throws IOException, ClassNotFoundException
●
Keep in mind inheritance hierarchy:
If method can throw an IOException and FileNotFoundException, only use
IOException
04/24/2019 HILMY A. TAWAKAL 14
Syntax: Exception Specification
●
accessSpecifier returnType methodName(parameterType
parameterName, . . .)
throws ExceptionClass, ExceptionClass, . . .
●
Example:
public void read(BufferedReader in)
throws IOException
●
Purpose:
To indicate the checked exceptions that this method can throw
04/24/2019 HILMY A. TAWAKAL 15
Catching Exceptions
●
Install an exception handler with try/catch statement
●
try block contains statements that may cause an
exception
●
catch clause contains handler for an exception type
04/24/2019 HILMY A. TAWAKAL 16
Catching Exceptions
●
Example:
try
{
String filename = . . .;
FileReader reader = new FileReader(filename);
Scanner in = new Scanner(reader);
String input = [Link]();
int value = [Link](input);
. . .
}
catch (IOException exception)
{
[Link]();
}
catch (NumberFormatException exception)
{
[Link]("Input was not a number");
}
04/24/2019 HILMY A. TAWAKAL 17
Catching Exceptions
●
Statements in try block are executed
●
If no exceptions occur, catch clauses are skipped
●
If exception of matching type occurs, execution jumps to catch clause
●
If exception of another type occurs, it is thrown until it is caught by
another try block
●
catch (IOException exception) block
– exception contains reference to the exception object that was thrown
– catch clause can analyze object to find out more details
– [Link](): printout of chain of method calls that lead to exception
04/24/2019 HILMY A. TAWAKAL 18
Syntax: General Try Block
try
{
statement
statement
. . .
}
catch (ExceptionClass exceptionObject)
{
statement
statement
. . .
}
catch (ExceptionClass exceptionObject)
{
statement
statement
. . .
}
. . .
04/24/2019 HILMY A. TAWAKAL 19
Syntax: General Try Block
●
Example:
try
{
[Link]("How old are you?");
int age = [Link]();
[Link]("Next year, you'll be " + (age + 1));
}
catch (InputMismatchException exception)
{
[Link]();
}
04/24/2019 HILMY A. TAWAKAL 20
Syntax : General Try Block
●
Purpose:
To execute one or more statements that may generate exceptions. If an
exception occurs and it matches one of the catch clauses, execute the first
one that matches. If no exception occurs, or an exception is thrown that
doesn't match any catch clause, then skip the catch clauses.
04/24/2019 HILMY A. TAWAKAL 21
Demo
04/24/2019 HILMY A. TAWAKAL 22
Exercise
[Link](null, "Invalid Input");
04/24/2019 HILMY A. TAWAKAL 23
The finally Clause
●
Exception terminates current method
●
Danger: Can skip over essential code
●
Example:
reader = new FileReader(filename);
Scanner in = new Scanner(reader);
readData(in);
[Link](); // May never get here
●
Must execute [Link]() even if exception happens
●
Use finally clause for code that must be executed "no matter what"
04/24/2019 HILMY A. TAWAKAL 24
The finally Clause
FileReader reader = new FileReader(filename);
try
{
Scanner in = new Scanner(reader);
readData(in);
}
finally
{
[Link](); // if an exception occurs, finally clause is also
// executed before exception is passed to its handler
}
04/24/2019 HILMY A. TAWAKAL 25
The finally Clause
●
Executed when try block is exited in any of three
ways:
– After last statement of try block
– After last statement of catch clause, if this try block caught an
exception
– When an exception was thrown in try block and not caught
●
Recommendation: don't mix catch and finally clauses
in same try block
04/24/2019 HILMY A. TAWAKAL 26
Syntax: The finally Clause
try
{
statement
statement
. . .
}
finally
{
statement
statement
. . .
}
04/24/2019 HILMY A. TAWAKAL 27
Syntax: The finally Clause
●
Example:
FileReader reader = new FileReader(filename);
try
{
readData(reader);
}
finally
{
[Link]();
}
04/24/2019 HILMY A. TAWAKAL 28
Syntax: The finally Clause
●
Purpose:
●
To ensure that the statements in the finally clause are
executed whether or not the statements in the try block
throw an exception.
04/24/2019 HILMY A. TAWAKAL 29
Designing Your Own Exception Types
●
You can design your own exception types–subclasses of Exception or RuntimeException
if (amount > balance)
{
throw new InsufficientFundsException(
"withdrawal of " + amount + " exceeds balance of " + balance);
}
●
Make it an unchecked exception–programmer could have avoided it by calling getBalance
first
●
Extend RuntimeException or one of its subclasses
●
Supply two constructors
– Default constructor
– A constructor that accepts a message string describing reason for exception
04/24/2019 HILMY A. TAWAKAL 30
Designing Your Own Exception Types
public class InsufficientFundsException
extends RuntimeException
{
public InsufficientFundsException() {}
public InsufficientFundsException(String message)
{
super(message);
}
}
04/24/2019 HILMY A. TAWAKAL 31
Demo
04/24/2019 HILMY A. TAWAKAL 32
Exercise
04/24/2019 HILMY A. TAWAKAL 33