Data Structures and Abstractions with Java ™
5th Edition
Module 2
Exceptions
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Exceptions
An exception is an object that describes
an unusual or erroneous situation
Exceptions are thrown by a program,
and may be caught and handled by
another part of the program
A program can be separated into a
normal execution flow and an exception
execution flow
Exception Handling
Java has a predefined set of
exceptions and errors that can occur
during execution
A program can deal with an exception
in one of three ways:
◦ ignore it
◦ handle it where it occurs
◦ handle it an another place in the
program
The manner in which an exception is
processed is an important design
Exception Handling
Ifan exception is ignored by the
program, the program will terminate
abnormally and produce an appropriate
message
The message includes a call stack trace
that:
◦ indicates the line on which the
exception occurred
◦ shows the method call trail that lead
to the attempted execution of the
offending line
The Basics
• Method creates an exception object
– We say “throws an exception”
• Signal to program
– Unexpected has happened
• Handle the exception
– Detect and react
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Checked and Unchecked
Exceptions
• Two types of exceptions:
• Checked
o The compiler checks that you don’t ignore them
o Due to external circumstances that the programmer cannot prevent
o Majority occur when dealing with input and output
o For example, IOException
• Unchecked
o Extend the class RuntimeException or Error
o They are the usually programmer’s or user’s fault
o Examples of runtime exceptions:
NumberFormatException
IllegalArgumentException
NullPointerException
o Example of error:
OutOfMemoryError
Checked Exceptions
A checkedexception either must be caught by a
method, or must be listed in the throws clause of any
method that may throw or propagate it
A throws clause is appended to the method header
Thecompiler will issue an error if a checked
exception is not caught or asserted in a throws
clause
Usedprimarily when programming with files and
streams
Scanner in = new Scanner(System.in);
Throws clause
• Two choices:
1. Handle the exception
2. Tell compiler that you want the method to be terminated
when the exception occurs
• 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
Suppose a method calls the Scanner constructor,
which can throw a FileNotFoundException, and
the nextInt method of the Scanner class, which can
cause a NoSuchElementException or
InputMismatchException.
Which exceptions should be included in the throws
clause?
FileNotFoundException,
NoSuchElementException
InputMismatchException.
You must include the
FileNotFoundException and you
may include the
NoSuchElementException if you
consider it important for
documentation purposes.
InputMismatchException is a
subclass of
NoSuchElementException.
It is your choice whether to include it.
The Basics
• Checked exceptions in the Java Class Library
– ClassNotFoundException
– FileNotFoundException
– IOException
– NoSuchMethodException
– WriteAbortedException
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
The Basics
• Runtime exceptions in the Java Class Library
– ArithmeticException
– ArrayIndexOutOfBoundsException
– ClassCastException
– IllegalArgumentException
– IllegalStateException
– IndexOutOfBoundsException
– NoSuchElementException
– NullPointerException
– StringIndexOutOfBoundsException
– UnsupportedOperationException
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Java Class Exception and Error Hierarchy
FIGURE J2-1 The hierarchy of some standard exception and error classes
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
The try Statement
To handle an exception in a program, the line that throws
the exception is executed within a try block
A try block is followed by one or more catch clauses
Each catch clause has an associated exception type and
is called an exception handler
When an exception occurs, processing continues at the
first catch clause that matches the exception type
Handling an Exception
• Postpone handling: The throws clause
– If programmer not sure what action is best for a client
when an exception occurs
– Leave the handling of the exception to the method’s
client
• Method that can cause but does not handle checked
exception must declare in its header
public String readString(. . .) throws IOException
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Handle It Now: The try-catch Blocks
try
{
< Possibly some code >
anObject.readString(. . .); // Might throw an IOException
< Possibly some more code >
}
catch (IOException e)
{
< Code to react to the exception, probably including the following statement: >
System.out.println(e.getMessage());
}
Code to handle an IOException as a result of invoking the method readString
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Multiple catch Blocks
catch (FileNotFoundException e)
{
. . .
}
catch (IOException e) // Handle all other IOExceptions
{
. . .
}
Good order for catch blocks
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Catching Exceptions
• Example:
try
{
String filename = ...;
FileReader reader = new FileReader(filename);
Scanner in = new Scanner(reader);
String input = in.next();
int value = Integer.parseInt(input);
...
}
catch (IOException exception)
{
exception.printStackTrace();
}
catch (NumberFormatException exception)
{
System.out.println("Input was not a number");
}
Catching Exceptions
The code can exit the try/catch block in
several ways:
1. The code inside the try block successfully ends
and the program continues with next executable
line after the catch clauses.
2. The code inside the try block runs into a return
statement and returns to the calling method.
3. The code inside the try block throws an exception
and control goes to the matching catch block.
4. The code inside the try block throw an exception,
but there are no matching catch blocks, returns to
the calling method and looks for a matching control
block. If none of the enclosing method calls catch
the exception, the program terminates.
Catching Exceptions
try
{
String filename = ...;
FileReader reader = new FileReader(filename);
Scanner in = new Scanner(reader);
String input = in.next();
int value = Integer.parseInt(input);
. . .
if (. . .) return; 2
. . .
1
}
catch (IOException exception)
{
exception.printStackTrace();
}
catch (NumberFormatException exception)
{
System.out.println("Input was not a number");
}
Catching Exceptions
try
{
String filename = ...;
FileReader reader = new FileReader(filename);
Scanner in = new Scanner(reader);
String input = in.next();
Exception raised int value = Integer.parseInt(input);
. . .
if (. . .) return;
. . .
catch (IOException exception)
{
exception.printStackTrace();
}
catch (NumberFormatException exception)
{
3
System.out.println("Input was not a number");
}
public void getInput()
{
try
{
Scanner in = new Scanner(System.in);
System.out.print(“Enter filename “);
String filename = in.next();
read(filename);
}
catch (NumberFormatException exception)
{
4
System.out.println("Input was not a number");
}
}
public void read(String filename){
try
{
String filename = ...;
FileReader reader = new FileReader(filename);
Scanner in = new Scanner(reader);
Exception raised String input = in.next();
int value = Integer.parseInt(input);
. . .
if (. . .) return;
. . .
}
catch (IOException exception)
No matching block {
exception.printStackTrace();
}
}
Catching Exceptions
The order of the catch statements may be important
if the exceptions being caught belong to the same
inheritance branch.
For example, the class EOFException is a subclass
of the more generic IOException, and you have to
put the catch block for the subclass first.
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);
reader.close(); // May never get here
• Must execute reader.close() even if exception
happens
• Use finally clause for code that must be executed
“no matter what”
The finally Clause
FileReader reader = new FileReader(filename);
try
{
Scanner in = new Scanner(reader);
readData(in);
}
finally
{
reader.close();
// if an exception occurs, finally clause
// is also executed before exception
// is passed to its handler
}
The finally Clause
• Executed when try block is exited in any of three
ways:
1. After last statement of try block
2. After last statement of catch clause, if this try block
caught an exception
3. When an exception was thrown in try block and not
caught
Something to consider!
Why was the out variable declared outside the try
block?
Answer: If it had been declared inside the try block,
its scope would only have extended to the end of the
try block, and the finally clause could not have
closed it.
Throwing an Exception
• A method intentionally throws an exception by executing
a throw statement.
• Programmers usually create the object within the throw
statement
throw new IOException();
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Throwing an Exception
• If you can resolve unusual situation in a reasonable
manner
– likely can use a decision statement
• If several resolutions to abnormal occurrence possible,
and you want client to choose
– Throw a checked exception
• If a programmer makes a coding mistake by using your
method incorrectly
– Throw a runtime exception
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Designing Your Own Exception
Types
• You can design your own exception types —
subclasses of Exception or RuntimeException
• Extend RuntimeException or one of its subclasses
• Supply two constructors
1. Default constructor
2. A constructor that accepts a message string describing
reason for exception
public class InsufficientFundsException
extends RuntimeException
{
public InsufficientFundsException() {}
public InsufficientFundsException(String message)
{
super(message);
}
}
Designing Your Own Exception
Types
• Throw an exception object to signal an exceptional
condition
• Example: InsufficientFundsException
InsufficientFundsException exception
= new InsufficientFundsException("Amount
exceeds balance");
throw exception;
• Anonymous exception (has no name):
throw new InsufficientfundsException("Amount
exceeds balance");
• When an exception is thrown, method terminates
immediately
Designing Your Own Exception
Types
public class BankAccount
{
public void withdraw(double amount)
{
try
{
if (amount > balance)
{
throw new InsufficientFundsException
("Amount exceeds balance");
}
balance = balance – amount;
}
catch (InsufficientFundsException exception)
{
exception.printStackTrace();
}
}
...
}
Suppose you construct a new bank account object with a zero balance and
then call withdraw(10). What is the value of balance afterwards?
public class BankAccount
{
public void withdraw(double amount)
{
try
{
if (amount > balance)
{
throw new InsufficientFundsException
("Amount exceeds balance");
}
balance = balance – amount;
}
catch (InsufficientFundsException exception)
{
exception.printStackTrace();
}
} The balance is still zero
... because the last statement of the
} withdraw method was never
executed.
Example of exception handled in different place than discovered
GUI Driver Data Manager Data Element
Bank Bank Account
Arraylist <BankAccount>
Extracts withdraw
amount and account
number from user int withdraw(acct, amt)
{
Displays new int withdraw(amt)
balance to user {
}
}
Normal execution flow
Example of exception handled in different place than discovered
GUI Driver Data Manager Data Element
Bank Bank Account
Arraylist <BankAccount>
try {
Extracts withdraw
amount and account
int withdraw(acct, amt) throws IFE
number from user
{
Displays new int withdraw(amt) throws IFE
balance to user {
if amt > balance
} throw IFE;
catch (IFE) no catch for IFE
} no catch for IFE
}
This is where is exception is discovered
This is where is exception can be resolved
Exception execution flow
Programmer-Defined Exception Classes
/** A class of runtime exceptions thrown when an attempt
is made to find the square root of a negative number. */
public class SquareRootException extends RuntimeException
{
public SquareRootException()
{
super("Attempted square root of a negative number.");
} // end default constructor
public SquareRootException(String message)
{
super(message);
} // end constructor
} // end SquareRootException
LISTING JI3 -1 The exception class SquareRootException
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Programmer-Defined Exception Classes
public class OurMath
{
/** Computes the square root of a nonnegative real number.
@param value A real value whose square root is desired.
@return The square root of the given value.
@throws SquareRootException if value < 0. */
public static double squareRoot(double value) throws SquareRootException
{
if (value < 0)
throw new SquareRootException();
else
return Math.sqrt(value);
} // end squareRoot
// < Other methods not relevant to this discussion are here. >
} // end OurMath
LISTING JI3-2 The class OurMath and its static method squareRoot
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Programmer-Defined Exception Classes
/** A demonstration of a runtime exception using the class OurMath. */
public class OurMathDriver
{
public static void main(String[] args)
{
System.out.print("The square root of 9 is ");
System.out.println(OurMath.squareRoot(9.0));
System.out.print("The square root of -9 is ");
System.out.println(OurMath.squareRoot(-9.0));
System.out.print("The square root of 16 is ");
System.out.println(OurMath.squareRoot(16.0));
} // end main
} // end OurMathDriver
Program Output
The square root of 9 is 3.0
The square root of -9 is Exception in thread "main" SquareRootException:
Attempted square root of a negative number.
at OurMath.squareRoot(OurMath.java:14)
at OurMathDriver.main(OurMathDriver.java:12)
LISTING JI3 -3 A driver for the class OurMath
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Programmer-Defined Exception Classes
/** A class of static methods to perform various mathematical
computations, including the square root. */
public class JoeMath
{
/** Computes the square root of a real number.
@param value A real value whose square root is desired.
@return A string containing the square root. */
public static String squareRoot(double value)
{
String result = "";
try
{
Double temp = OurMath.squareRoot(value);
result = temp.toString();
}
catch (SquareRootException e)
{
Double temp = OurMath.squareRoot(-value);
result = temp.toString() + "i";
}
return result;
} // end squareRoot
// < Other methods not relevant to this discussion could be here. >
} // end JoeMath
LISTING JI3 -4 The class JoeMath
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Programmer-Defined Exception Classes
/** A demonstration of a runtime exception using the class JoeMath. */
public class JoeMathDriver
{
public static void main(String[] args)
{
System.out.print("The square root of 9 is ");
System.out.println(JoeMath.squareRoot(9.0));
System.out.print("The square root of -9 is ");
System.out.println(JoeMath.squareRoot(-9.0));
System.out.print("The square root of 16 is ");
System.out.println(JoeMath.squareRoot(16.0));
System.out.print("The square root of -16 is ");
System.out.println(JoeMath.squareRoot(-16.0));
} // end main
} // end JoeMathDriver
Program Output
The square root of 9 is 3.0
The square root of −9 is 3.0i
The square root of 16 is 4.0
The square root of −16 is 4.0i
LISTING JI3 -5 A driver for the class JoeMath
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Inheritance and Exceptions
public class SuperClass
{
public void someMethod() throws Exception1
{
} // end someMethod
} // end SuperClass
public class SubClass extends SuperClass
{
public void someMethod() throws Exception1, Exception2 // ERROR!
{
} // end someMethod
} // end SubClass
Consider this superclass and subclass — cannot override someMethod
in a subclass and list additional checked exceptions in its throws clause
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Inheritance and Exceptions
public class Driver
{
public static void main(String[] args)
{
SuperClass superObject = new SubClass();
try
{
superObject.someMethod();
}
catch (Exception1 e)
{
System.out.println(e.getMessage());
}
} // end main
} // end Driver
Only Exception1 is caught. If the throws clause in SubClass was legal,
we could call SubClass’s someMethod without catching Exception2.
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Inheritance and Exceptions
public class SuperClass
{
public void someMethod() throws Exception1
{
} // end someMethod
} // end SuperClass
public class SubClass extends SuperClass
{
public void someMethod() throws Exception2 // OK, assuming Exception2
{ // extends Exception1
} // end someMethod
} // end SubClass
If Exception2 extends Exception1, the above is legal
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved