Chapter 12 – Exception Handling
Introduction to Exceptions
· Exceptions and the Exception class
· How to use the try code to throw and catch exceptions
· How to use the Exception getMessage( ) method
· Throwing and catching multiple Exceptions
· The finally block
· The limitations of traditional methods of exception handling
· How to specify the Exceptions a method can throw
· How to handle the same Exception uniquely with each throw
· How to trace exceptions through the call stack
· How to create your own Exception subclasses
It would be very useful to outline with
students the types of errors various types of
statements can throw, and
the most typical exceptions thrown:
· Any statement using an array – an array index out of bounds
· Any statement with division– division by zero
· Any
input statement – a number of data input errors (eg double data input as
integer, String as integer,
and so on.
Note that there are over 30 Exceptions, from which the program
can recover. Errors (such as incorrect file
names, incorrect file formats, incorrect file paths, and so on) are not
recoverable.
Differentiate between logic errors in the program and data input
that causes these errors to occur. Precise
algorithms and tight coding avoid logic errors. Data input errors must be
taken into account in order to have robust programs.
All IO Exceptions, including keyboard and file exceptions, must
be thrown. These exceptions are the most
likely exceptions to be thrown, as they involve user entry. Bad data entered by
users, either through the keyboard or from a data file, must be handled in order
to make the program robust. Remind students that a user would not want a program
to "crash" (i.e., return to the operating system) anytime a typing
error occurs.
Using programmer defined exceptions allow the programmer to guard
against technically correct but logically
incorrect data from being processed. The Java language, for example, allows a
wide range of data to be entered as an integer. A programmer creating an
application for a payroll program may wish to restrict the integer for number of
hours
worked to a set range. By creating an exception if the number of
hours worked is outside of that range,
logical errors (for example, paying an employee for 1000 hours in one week)
can be avoided.
I. Whenever a
computer program attempts to do something, the possibility of an
error is present. Java provides a Throwable class, which assists programmers in
making code more robust.
A. The Error
class is a child of the Throwable class. The Error class includes
serious errors from which a
program will probably not recover. These errors
include running out of
memory, not being able to find a file, attempting to use
a file that is unreadable,
and other internal errors.
B. The Exception
class is also a child of the Throwable class. These errors
are less serious, and with
the correct Exception handling, the program should be
able to continue. Exceptions
include illegal arithmetic operations (such as
division by zero), IO
errors, and array out of bounds.
C. When
unhandled errors and exceptions occur, the program will terminate
abruptly. Good programming
requires that this happens as little as possible.
The ability of the program to handle unusual occurrences is
called robustness.
II. Try and
Catch
A. The try and
catch blocks are used for exception handling. The first step is to
determine what type of
exception may be thrown by a set of code.
B. The try/catch
statements are coded as follows:
The method must include a throws exceptionType in
its header.
The try block:
try
{
Statements which could cause an exception
}
The catch block:
catch(exceptionName anExceptionInstance)
{
Statements to deal with the exception
}
C. Every try
must have at least one catch. If there is a catch, the method must
have a throws in the header.
D. All
exceptions have a String that is the official error message. Throwable has
a method called getMessage
that returns that String. To determine the actual
error,
exceptionInstance.getMessage(
); returns the String with the message.
III. Multiple
Exceptions.
A. You may
program a method that throws multiple exceptions with one try and
multiple catches. You may
have a catch block for each exception thrown.
B. You may also
program a method that throws multiple exceptions that have
multiple tries, one that
includes statements for every type of exception that can be
thrown, all of the
exceptions being caught by the same catch block.
IV. Finally
A. Use the finally
block following a try block and catch block sequence to code
any statements that must be
executed regardless of whether an exception was
thrown or not.
B. The finally
block allows the programmer to do cleanup routines even if the
method in which it resides
ends prematurely due to an exception.
Advanced Exceptions
I. Inefficient
error handling
A. Traditional
error handling required the use of complex, hard to understand
nested if statements.
B. Object
oriented error handling makes the coding cleaner and easier to
maintain.
II. Specifying
Exceptions
A. Not every
Exception needs to be thrown, and for simplicity’s sake, not all
Exceptions should be thrown.
Exceptions that must be thrown are:
· IOException – when using keyboard entry.·
IOException – when reading
data in from a file
· InterruptedException – when using threads
B. Not all
Exceptions that are thrown need to be caught. If an Exception is
caught, it need not be
handled by the method throwing the Exception.
C. For a method
to be used, the following pieces of information must be known:
(They are referred to as the
method’s signature)
· The return type
· The number, type and order of arguments to be passed
· The type and number of Exceptions thrown
If all of this is known, any class using the method can make
decisions about what
to do about any Exceptions that may be thrown.
III. Handling
Exceptions uniquely
A. Object
oriented programming makes Exception handling more powerful, as
classes may call methods which throw Exceptions that can be caught by the
calling class. Because of this, the programmer can deal with Exceptions in a manner
specific to the application.
IV. Tracing
Exceptions
A. When a
program executes, the statements execute in order. If a statement
within a method calls another method, execution continues with the called
method, and after it is completed, control returns to the original method that
performed the call. In object oriented programming, methods may call programs
within different classes.
B. When
attempting to debug programs that may throw Exceptions, the
complexity of control transfer makes it difficult to find the
source of the
Exception.
C. Programmers
can insert a statement within a catch block that will print out a
trace of the methods called, from most recent to original (usually main). This
tells the programmer which method threw the Exception. The format of the statement
is:
error.printStackTrace( );
with error the instance of the Throwable
error
V. Creating your
own Exceptions.
A. The Exception
class can be extended. This allows a programmer to set
specific rules on certain data within an application. By convention, new Exceptions
are named with Exception at the end of the name.
B. The new
Exception is created as a class with a constructor. This
constructor calls the super constructor from the Exception class.
Additional methods
and data are permitted, but not required.
Exercise 1.
public class GoTooFar
{
public static void
main(String[] args) throws NumberFormatException
{
int
num[] = {10,12,20,24,42};
int x =
0;
try
{
while(x<10)
{
System.out.println("Number is " + num[x]);
++x;
}
}
catch(ArrayIndexOutOfBoundsException error)
{
System.out.println("Now you've gone too far.");
}
}
}
Exercise 2.
public class
TryToParseString
{
public static void
main(String[] args) throws NumberFormatException
{
int num
= 13, denom = 0, result;
try
{
denom = Integer.parseInt("A");
result = num / denom;
}
catch(NumberFormatException error)
{
System.out.println("You can't use a letter.");
}
}
}
Exercise 3.
import java.io.*;
public class Exception1
{
public static void
main(String args[])
{
int g;
int
a[];
try
{
System.out.println("Enter a number from 1 to 9.");
g = System.in.read();
g = g-60;
a = new int[g];
}
catch(Exception e)
{
System.out.println("catch " + e.getMessage());
}
}
}
Exercise 4.
public class Exception2
{
Exception2 o;
Exception2()
{
m();
}
public
void m()
{
o.m();
}
public
static void main(String args[])
{
try
{
Exception2 o2 = new Exception2();
}
catch(Exception e)
{
System.out.println("catch " + e.getMessage());
}
}
}
Exercise 5.
import java.applet.*;
import java.awt.*;
public class Exception3
extends Applet
{
Label
l;
public
void init()
{
try
{
add(l);
}
catch(Exception e)
{
System.out.println("catch " + e.getMessage());
}
}
}