5 ExceptionHandling
5 ExceptionHandling
Chapter 10 (10.1-10.3)
CS 2334
University of Oklahoma
Brian F. Veale
Handling Errors in a Program
It is hard to make a program foolproof because
fools are so ingenious
Whenever programs run, there is a chance for
encountering errors
Opening a file that doesn’t exist
Removing an element from an empty List
Reading the 10th value of a nine element array
Small problems shouldn’t cause a program to halt
Should be detected and corrected
This technique is called “Exception Handling” in
Java
2
Exceptions
5
Exception Generation
7
Throwing Exceptions
displayFile()
openFile()
9
Handling Exceptions
10
Try and Catch
try and catch are used in order to detect and
recover from Exceptions
try signifies a block of code that has the potential to
throw an exception
One or more catch blocks immediately follow the
try block and are used to recover if there is an
exception
When an exception occurs, the code in the try
block halts immediately, and execution starts in the
following catch block
{ The system chooses the first catch block that
handles the exception that was thrown
11
Errors in the Demo Program
A problem occurs when the user enters the name of
a non-existing file
Two options:
{ Halt the program
{ Get the user to re-enter a valid file name
First choice is somewhat frustrating to user
{ They did, after all, want to see the contents of some
file, even if they got the name wrong
Second choice is better because problem goes
away if we have a valid file name
Example: FileDisplay2.java
12
Where is the error?
13
Solution
16
Code that uses Exceptions
public static void removeAll(List list)
{
try
{
//Infinite loop
while(true)
{
list.remove(list.size()-1);
}
}
catch (Exception exp)
{
System.out.println("The list is now empty");
}
}
17
What's wrong with this code?
Another version of removeAll()
public static void removeAll(List list)
{
while (!list.isEmpty())
{
list.remove(list.size()-1);
}
}
18
Using Exceptions Wisely
19
More on using Exceptions
They should not be used for inevitable conditions
{ Collections.binarySearch()
Returns -1 if the key is not found
Don't use Exceptions if you can handle the problem
without them
{ equals() method
{ compareTo() method
{ Collection.add() method
Returns false only if the collection does not allow duplicates
Returns true if the collection has changed as a result of the
call
20
Categories of Exceptions
21
Common Exceptions
Exceptions
{ ClassNotFoundException
{ CloneNotSupportedException
{ IOException
FileNotFoundException
RunTimeException
{ ArithmeticException
{ NullPointerException
{ ClassCastException
{ IllegalArgumentException
{ IndexOutOfBoundsException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
22
The Exception Hierarchy
23
Assertions
Assertion – a condition or statement about the state
of your program/code that should be true
In Java, this lets you test assumptions about your
program
{ such as the range an input value will have
Each assertion consists of a boolean expression
that you believe to be true when the assertion
executes.
{ It is not true, the system will throw an error.
Using assertions is one of the quickest and most
effective ways to detect and correct bugs.
24
The assert Statement
Form 1:
assert (Expression1)
Form 2:
assert (Expression1: Expression2)
Expression1 is a boolean expression that you believe to
be true.
Expression2 is an expression that has a value.
It cannot be an invocation of a method that is declared
void.
The second form can be used to provide a detailed
message for the AssertionError that will be thrown if
Expression1 is false.
25
Examples
assert speed <= SPEED_OF_LIGHT;
if( i % 3 == 0 )
{
...
}
else if( i % 3 == 1 )
{
...
}
else
{
assert ( i % 3 == 2 : i );
...
26
}
Another Example
switch( suit )
{
case Suit.CLUBS:
...
break;
case Suit.HEARTS:
...
break;
case Suit.DIAMONDS:
...
break;
case Suit.SPADES:
...
break;
default:
assert false: suit;
27
}
Enabling Assertions
29
Preconditions
Precondition – What must be true when a method is invoked.
Private Methods
{ Use assert statements to test preconditions.
{ Some people disagree with this.
{ Only methods inside the same class can call the method.
Public Methods
{ In a public method we must throw an exception if a
precondition fails.
{ Assertions are not enabled by default and we cannot
guarantee the user will enable them.
{ If we want to make sure the condition is true anytime the
method is called we must throw an exception instead of
using assert.
30
Precondition/Postcondition
Example
MyString.java
31
Sample Exercises
Chapter 10 Exercises
{ 4, 10
32