You are on page 1of 32

Exception Handling

and Assertions in Java

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

„ An unplanned event that lies outside of the


normal operation/usage of a program.
{ This is not simply a special case of an algorithm
or operation that should be handled as a normal
event inside the program.
„ The fact that an exception occurred may in
fact not be handled by the method in which
the exception occurred, it depends on the
situation.
3
Exception Handling

„ Used to detect anticipated and


unanticipated errors
„ If possible we will correct them so the
user can continue using the program
„ In the worst case, would like to
indicate the nature of the error
„ The Exception class is used to
indicate problems
4
The Exception Class
Checked exceptions –
exceptions that must
be caught or declared
in a program
Unchecked exceptions – serious
errors that typical program
should not have to handle

5
Exception Generation

„ When an error occurs…


{ An instance of the Exception class (or its
subclasses) is created
{ This instance is passed to the method
that had the problem
„ This is called “throwing” an exception
{ These instances contain useful
information about the nature of the
problem
6
When an error occurs…

„ When an exception is thrown, program


execution stops
{ Control is passed to the calling method
{ If the exception is not handled, the
process repeats
{ Eventually, the exception can reach the
main method and cause it to halt, ending
program execution

7
Throwing Exceptions

„ When we do not want to handle an


exception and want to pass it to the method
that calls our method, we throw the
exception.
„ Any method that may potentially throw an
Exception is required to declare this after
the method signature
public returnType myMethod() throws <ExceptionType>
„ Exception Demo: FileDisplay.java
8
Exception Propagation in the
Demo

Command line main() method

displayFile()

openFile()

9
Handling Exceptions

„ We want to avoid having an Exception


cause a program to crash
„ If error recovery is impossible, explain
the problem in a helpful manner
„ We must determine how to recover
from an error

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?

„ The error is found and handled in


openFile().
„ Does the mistake in the filename occur
in the main() method or in the
openFile() method?
„ Does this make sense?

13
Solution

„ It would be better to handle the error where


it is made, in the main() method
„ Makes it easier to modify the program in the
future
{ i.e., change the program from using console
input to GUI based
„ openFile() and displayFile() will still throw
the Exception
„ main() will handle the Exception
„ Example: FileDisplay3.java
14
catches, catches, and more
catches

„ You can associate multiple catch blocks with


a single try
„ These blocks must be ordered from most
specific to least specific.
{ A more general catch block may not handle a
specific error the way intended by the
programmer.
{ Compiler will probably catch your error
{ It is helpful to know the Exception Inheritance
Hierarchy
„ Example: MultipleCatch.java
15
finally!
„ Are we done yet?
„ The finally block is placed after the try and catch
blocks
{ The finally block is optional
„ The code in the finally block is guaranteed to be
executed no matter what happens in the try block
{ Can be used for cleanup after the try and catch blocks
finish
{ Executes no matter if an exception occurs or not.
„ Example: FileDisplay4.java

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);
}
}

Is this code any better? Why?

18
Using Exceptions Wisely

„ Exceptions can be expensive if used


poorly
{ Every time an exception is thrown a new
object is created in memory
„ Exceptions are not intended to handle
routine or expected conditions

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

„ Two broad types of Exceptions


{ Exceptions
„ Must be caught or thrown to a higher level in
the code they occur
{ RuntimeExceptions
„ Caused by software bug
„ Likely impossible to recover from
„ Do not need to be caught

21
Common Exceptions
„ Exceptions
{ ClassNotFoundException
{ CloneNotSupportedException
{ IOException
„ FileNotFoundException
„ RunTimeException
{ ArithmeticException
{ NullPointerException
{ ClassCastException
{ IllegalArgumentException
{ IndexOutOfBoundsException
„ ArrayIndexOutOfBoundsException
„ StringIndexOutOfBoundsException

22
The Exception Hierarchy

„ Some subclasses of Exception


{ For a list of subclasses that inherit from
Exception go to
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Exception.html
{ For a list of subclasses that inherit from
RunTimeException go to
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/RuntimeException.html
{ If you are using a particular class and want to know what
types of exceptions it can throw when you invoke it's
methods, look at it's page in the Java API
„ Example: ListIterator -
http://java.sun.com/j2se/1.5.0/docs/api/java/util/ListIterator.html
„ Look at set() and add()

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

„ By default assertions are not enabled at run-


time.
„ Assertions are enabled by passing the
parameter -ea to the Java Virtual Machine
{ java -ea MyAppName
„ When assertions are disabled there is
virtually no performance lost due to the
existence of assertions in the code.
{ They are treated like empty statements.
28
Postconditions

„ Postcondition – What must be true


after a method successfully completes.
„ We can test Postconditions with an
assert statement.

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

You might also like