Lecture 9 - University of Virginia

Download Report

Transcript Lecture 9 - University of Virginia

Lecture 9:
Exceptions in Java
CS201j: Engineering Software
University of Virginia
Computer Science
Joel Winstead
http://www.cs.virginia.edu/~jaw2u
Menu
•
•
•
•
What are exceptions?
Declaring, using, and handling exceptions
Exceptions in specifications
Defensive Programming
26 September 2002
CS 201J Fall 2002
2
What is an exception?
public class AverageLength {
public static void main (/*@non_null@*/ String args[])
{
String filename = args[0];
…
}
}
> javac AverageLength.java
> java AverageLength
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
at AverageLength.main(AverageLength.java:7)
26 September 2002
CS 201J Fall 2002
3
What happened?
• We called the program with no arguments,
so the args[] array is empty
• We then tried to access args[0]
• Does it make sense to ask for the first
element of an empty array?
26 September 2002
CS 201J Fall 2002
4
Exceptions
• An exception indicates that something
abnormal has happened
• This could mean an error in the program
• But not necessarily:
– It could represent an undefined value of a
method call
– It could indicate some other special condition,
such as FileNotFoundException
26 September 2002
CS 201J Fall 2002
5
Handling Exceptions
• If an exception occurs, and we don’t do
anything about it, the program stops.
• This isn’t always what we want:
– If there is an error, we may be able to fix it,
report it, or degrade gracefully
– If there is some other special condition, we
may need to take note of this and continue
processing
26 September 2002
CS 201J Fall 2002
6
Try and Catch
try {
file = new FileReader(filename);
} catch (FileNotFoundException e) {
System.out.println(“Could not open “+filename);
System.exit(1);
}
• The try clause indicates what to attempt to do
• The catch clause specifies:
– An exceptional case
– What to do if that exceptional case occurs
26 September 2002
CS 201J Fall 2002
7
Try and Catch
try {
file = new FileReader(filename);
} catch (FileNotFoundException e) {
System.out.println(“Could not open “+filename);
System.exit(1);
}
• If the try clause finishes normally
– The catch clause is ignored
• If the try clause throws an exception,
– The system looks for a matching catch clause
– If one exists, it is executed, i.e. it handles the exception
26 September 2002
CS 201J Fall 2002
8
Throwing Exceptions
• Some operations in Java generate
exceptions automatically
• We can also throw exceptions explicitly:
public float sqrt(float value) {
if (value < 0.0) {
throw new Exception(“Value is negative”);
} else {
...
}
}
26 September 2002
CS 201J Fall 2002
9
Exception Propagation
public first_method() {
try {
second_method();
} catch (MyException e) {
System.out.println(
“A MyException occurred”);
}
}
public second_method() {
try {
throw new MyException();
} catch (SomeOtherException e) {
System.out.println(
“An exception occurred”);
}
}
• What should happen here?
26 September 2002
CS 201J Fall 2002
10
Exception Propagation
public first_method() {
try {
second_method();
} catch (MyException e) {
System.out.println(
“A MyException occurred”);
}
}
•
•
•
•
•
public second_method() {
try {
throw new MyException();
} catch (SomeOtherException e) {
System.out.println(
“An exception occurred”);
}
}
first_method calls second_method
second_method throws a MyException
The catch clause in second_method does not match
The catch clause in first_method does match
The handler for MyException in first_method is executed to handle
the exception
26 September 2002
CS 201J Fall 2002
11
Exception.printStackTrace()
• When an exception occurs, we can call
e.printStackTrace() to find out what
happened:
try {
int a[] = new int[10];
a[17] = 1;
} catch (Exception e) {
System.err.println(e.toString());
e.printStackTrace();
}
26 September 2002
java.lang.ArrayIndexOutOfBoundsException
at foo.main(foo.java:5)
CS 201J Fall 2002
12
Declaring our own exceptions
• We can also declare our own exception types:
public class MyException extends Exception { }
• Why would we do this?
– If a method is not defined for all cases, it makes
sense to throw an exception rather than a
meaningless value
– It allows a program to indicate the nature of an error
– It allows the program to indicate special, but non-error
conditions
26 September 2002
CS 201J Fall 2002
13
Example
class ElementNotFoundException extends Exception { }
class IntList {
int array[];
int n;
public int getElementIndex(int element)
throws ElementNotFoundException {
for (int i=0; i<array.length; i++) {
if (array[i] == element) {
return i;
}
}
throw new ElementNotFoundException();
}
26 September 2002
CS 201J Fall 2002
14
Checked vs. Runtime
Exceptions
• Checked exceptions must be caught in a
try..catch, or explicitly propagated:
public int getIndex(String element)
throws ElementNotFoundException {
...
}
– The Java compiler enforces this
• Java does not require RuntimeExceptions
to be declared, but it is a good idea
– ESC/Java does require this
26 September 2002
CS 201J Fall 2002
15
Exception Type Hierarchy
• Throwable
– Error
– Exception
• RuntimeException
• We can add our own exceptions to the
hierarchy when we declare them:
class MyRuntimeException extends RuntimeException { }
26 September 2002
CS 201J Fall 2002
16
Generic Catch Clauses
• A catch clause can match subtypes of
exceptions:
public class GeneralException extends Exception { }
public class SpecificException extends GeneralException { }
...
try {
throw new SpecificException();
} catch (GeneralException ge) {
ge.printStackTrace();
}
26 September 2002
CS 201J Fall 2002
17
Built-in Exception Types
• Checked Exceptions:
– FileNotFoundException
– IOException
• EndOfFileException
• Runtime Exceptions:
– ArrayIndexOutOfBoundsException
– NullPointerException
26 September 2002
CS 201J Fall 2002
18
Exceptions in Abstractions
• The exceptional behavior of a method is
part of the abstraction it implements
• The kinds of exceptions a method might
throw, and what they mean, are just as
important to understand as the normal
return value
• What could happen if we use a method,
but don’t understand what exceptions it
might throw, and don’t handle them?
26 September 2002
CS 201J Fall 2002
19
Unhandled Runtime Exceptions
The Ariane V
26 September 2002
CS 201J Fall 2002
20
Exceptions in Specifications
• Java requires us to declare checked exceptions
in a method’s throws clause
• ESC/Java requires both checked and runtime
exceptions to be declared
• ESC/Java can be used to prove that certain
runtime exceptions are not possible
• ESC/Java annotations can be used to specify
what should be true when an exception is
thrown
26 September 2002
CS 201J Fall 2002
21
Proving Absence of Exceptions
public int getElementIndex(int array[],int element)
//@ requires array != null
{
for (int i=0; i<array.length; i++) {
if (array[element] == i) {
return i;
}
}
}
• Without
this, ESC/Java issues a warning:
Warning: possible null dereference (Null)
for (int i=0; i < array.length; i++) {
^
26 September 2002
CS 201J Fall 2002
22
Defensive Programming
• It is better to catch errors early
• We can catch errors early if we add extra
checks to the program for things that
should not happen
• We can use exceptions to do this
26 September 2002
CS 201J Fall 2002
23
Checking Requirements
• We can verify the precondition of a
method and throw an exception if it fails:
public int getIndex(int array[], int element)
throws PreconditionNotMetException
//@ requires array != null
//@ ensures array[\result] == element
{
if (array == null) {
throw new PreconditionNotMetException(“array != null”);
} else {
...
}
26 September 2002
CS 201J Fall 2002
24
Checking Invariants
• We can also check a rep invariant and
throw an exception if it fails:
public class IntList {
int array[];
int n;
//@ invariant array != null && 0 <= n && n <= array.length
public void addElement(int new_element) {
if (array == null || n < 0 || n > array.length) {
throw new InvariantFailureException();
}
....
}
26 September 2002
CS 201J Fall 2002
25
Summary
• Exceptions indicate abnormal or special
conditions in a program
• Exceptions propagate up the call chain until a
matching handler is found
• Exceptions are objects
• Exceptional cases are part of the abstraction,
and should be part of specifications
• Exceptions can be used in defensive
programming to catch mistakes early
26 September 2002
CS 201J Fall 2002
26
Charge
• Coach Dave will have office hours on
Friday from 3:30 to 4:30pm to give back
design documents for PS4 and answer
any questions about them
26 September 2002
CS 201J Fall 2002
27