07.Exceptions - Calvin College

Download Report

Transcript 07.Exceptions - Calvin College

Errors & Exceptions
Joel Adams and Jeremy Frens
Calvin College
(1/18)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Review: Inheritance
We’ve seen that classes can be organized into hierarchies…
Person
Employee
Salaried
Employee
Manager Engineer
(2/18)
Hourly
Employee
Intern
2003 Joel C. Adams. All Rights Reserved.
Temp
Designing your
system to take
maximum
advantage of
inheritance is
what distinguishes
OOP from
traditional
programming.
Dept of Computer Science
Calvin College
Inheritance within Java
In Java, Object is the superclass of every other class:
Object
Component
Container
Number
Double Integer
JComponent
(3/18)
Long
Exception
Error
IO
Runtime
Exception Exception
AbstractButton
JButton
Throwable
There are many Exception subclasses
(see the API).
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Errors
Error and its subclasses describe internal errors and
resource exhaustion within the Java Runtime Environment.
In such situations, there is little a
program can do but print a diagnostic
and terminate gracefully.
Error-handling is not an API
programmer’s responsibility, and
only the Java Runtime
Environment should throw them.
Object
Throwable
Exception
Error
IO
Runtime
Exception Exception
For this reason, we’ll focus on Exceptions…
(4/18)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Exceptions
Exception subclasses can be divided into two categories:
 RuntimeException - the result of programmer error:
 out of bounds List access (IndexOutOfBoundsException)
 null pointer access (NullPointerException)
 bad cast (ClassCastException)
…
All the other Exception subclasses:
 trying to read past end-of-file (EOFException)
 trying to open a malformed URL (MalformedURLException)
 Trying to instantiate a class (from a string) that does not exist
(ClassNotFoundException)
…
(5/18)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Why Exceptions?
Old-fashioned languages just display-error-and-die (DEAD)
when an exceptional situation occurs:
if ( somethingBadHappened() ) {
/* C */
fprintf(stderr, "Something bad happened");
exit(1);
}
An OO language treats exceptions as objects:
A method that detects the exceptional situation can throw
an exception; and
The caller of such a method can catch the exception.
 The decision on how to respond is left to the caller.
(6/18)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Throwing Exceptions
Instead of DEAD-ing, we can throw an exception:
if ( somethingBadHappened() ) {
// Java
throw new Exception("Something went wrong");
}
You can throw whatever kind of exception is appropriate
(Exception, RuntimeException, IOException, …)
for a given situation.
How do you know what kinds of exceptions are available?
 The API, which also describes the available constructors
(7/18)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Throwing Exceptions (ii)
A method that throws an exception may (and sometimes
must) advertise that it does so by including a throws clause:
void swap(int i, int j)
throws ArrayIndexOutOfBoundsException {
if (i < 0 || i >= myArray.length ||
j < 0 || j >= myArray.length ) {
throw new ArrayIndexOutOfBoundsException();
}
// ... Exchange the values at indices i & j
}
A method also needs a throws clause if it invokes a method
that throws an exception that it doesn’t want to handle…
(8/18)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Exercise: Part I
Go to today’s exercise and complete part I
(on throwing exceptions)…
(9/18)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Catching Exceptions
Many of Java’s predefined methods throw exceptions…
A program that invokes such a method must either
catch and handle the exception, or
propogate (and advertise) the exception.
To catch/handle an exception, you use a try-catch block:
try {
// statements that might throw an exception
}
catch (Exception e) {
// statements to handle e
}
(10/18)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Example
If a piece of code can potentially throw multiple exceptions,
a try block can have multiple catch blocks:
void print(Stack s, PrintWriter out) {
try {
while (true) {
Integer n = (Integer) s.pop();
out.println(n);
}
}
catch(IOException e1) {
// handle problem writing to out
}
catch (EmptyStackException e2) {
// handle empty stack
}
}
(11/18)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Exercise: Part II
Go to today’s exercise and complete part II
(on catching exceptions)…
(12/18)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Defining Your Own Exceptions
If no predefined exception is appropriate for your situation,
you can always use inheritance to define your own:
public
class EmptyQueueException extends RuntimeException {
public EmptyQueueException() { super(); }
public EmptyQueueException(String msg) { super(msg); }
}
A user-defined exception should usually include:
 a default constructor, and
 a constructor that takes a message-string, but
they usually need to do nothing more than invoke super()
(as shown above).
(13/18)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Defining Your Own Exceptions (ii)
Your methods can then throw your exceptions:
public class Queue {
...
public Object getFront()
throws EmptyQueueException {
// optional
if ( this.isEmpty() ) {
throw EmptyQueueException("pop: queue is empty");
}
Object result = myArray[myHead];
myHead = (myHead + 1) % myArray.length;
return result;
}
}
(14/18)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Rules of Thumb
1. Don’t use exception-handling in place of a simple test.
 A simple test may be easier to write and execute.
2. Avoid multiple try-blocks per method.
1 try-block per method is usually all you need.
3. Avoid the temptation to write empty catch-blocks.
Handle exceptions appropriately.
4. If it is not your method’s responsibility to handle an
exception, don’t hesitate to propagate it.
You need not always handle an exception locally...
5. Don’t define too many exceptions (or you’ll be hated).
(15/18)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
The finally Clause
Sometimes, you need to perform a “cleanup” action
after you’ve handled an exception…
For such situations, Java provides the finally clause:
InputStream fin;
try {
// 1. code using fin, may throw an exception
} catch (IOException e1) {
// 2. handle e1
} finally {
// 3. ALWAYS cleanup at the end
try { if (fin != null) fin.close(); }
catch(IOException e2) { // handle e2
}
}
(16/18)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Summary
In Java, exceptions provide an object-oriented way of dealing with
unusual circumstances.
A programmer can indicate that something abnormal has occurred by
throwing an exception.
A method that throws an exception must advertise it via a throws
clause.
A programmer can handle an exception using a try-catch block.
A programmer can define their own exceptions by extending an
appropriate class in the Exception hierarchy.
The finally clause lets you “clean up” after handling an exception.
(17/18)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Exercise: Part III
Go to today’s exercise and complete part III
(on defining your own exceptions)…
(18/18)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College