12-Handling Exceptions

Download Report

Transcript 12-Handling Exceptions

TCU CoSc 10403
Programming with Java
Handling Exceptions
What is an Exception
•
Imagine the following code that might appear in some Applet:
int age = Integer.parseInt(ageTF.getText().trim());
•
Obviously, we are expecting a number will appear in the
TextField and that it constitutes a legal integer age.
•
Consider, however, the following possibilities:
1.
What if the user types a “$” instead of a 4 by mistake?
2.
What if the user enters a decimal point number rather than
an integer?
3.
What if the user holds down the “3” key too long and an
extremely long number is accidentally entered?
•
We don’t expect circumstances such as these -- but they do
happen!
•
Software must be designed to expect the unexpected!!!
What is an Exception
•
Some things that can go wrong during the execution of a program
(such as on the earlier slide) can’t be detected at compile-time —
because the user has not yet made the mistake by entering the
wrong data!!
•
Another example: your program may attempt to divide one
number by zero (ex. examSum/numberOfStudents)
•
Or your program may require that an integer value be entered into
a TextField, and the user of the program enters a float value or
some other illegal character.
•
From the compiler’s point of view, there is nothing wrong with
these statements, and problems will arise only when the program
is actually executing.
•
At that point an internal alarm goes off, and Java attempts to
“throw an exception” signifying that something untoward has
occurred.
Example
import java.awt.*;
import java.applet.*;
public class TrivialApplet extends Applet
{
//------------------------------// Deliberately divides by zero
// to produce an exception.
//------------------------------public void init()
{
int numerator = 10;
int denominator = 0;
System.out.println ("This text will be printed.");
System.out.println (numerator / denominator);
System.out.println ("This text will not be printed.");
//
//
//
//
because exception
occurs prior to
execution of this
statement
}
}
Note also:
There is no code to handle the exception, if it occurs!
What is an Exception
•
The system then immediately halts its normal mode of execution
and goes off looking for help.
•
With luck, the system will find some code in your program that
will catch the exception and deal with it.
•
Once caught, the alarm is silenced and the system picks up
execution at a location after the block that contained the offending
statement.
•
Jargon:
Java has its own terminology for exceptions.
Exceptions are indicted by being thrown, and are detected
elsewhere by being caught.
Terminology of Exceptions
•
An exception is an object that describes an unusual
or erroneous situation
•
Exceptions are thrown by a program, and may be
caught and handled by another part of the program
•
A program can be separated into a normal execution
flow and an exception execution flow
•
An error is also represented as an object in Java,
but usually represents an unrecoverable situation
and should not be caught
Some Possible Exceptions
ArithmeticException
- something, such as division by zero,
has gone wrong in an arithmetic
expression
NumberFormatException
- indicates that an illegal number format
is being used.
StringIndexOutOfBoundsException - an attempt has been made to use an
inappropriate String index.
NullPointerException
- a class method is being called by an
object instance that is currently null.
EOFException
- an end-of-file mark has been seen.
IllegalArgumentException
- a method has been called with an
invalid argument.
IndexOutOfBoundsException
- an index into an array is out of bounds.
Exceptions
•
As indicated on the earlier slide, Java has a
predefined set of exceptions and errors that can occur
during execution
•
A program can deal with an exception in one of three
ways:
ignore it
 handle it where it occurs
 handle it in another place in the program

•
The manner in which an exception is processed is an
important design consideration
Exceptions
•
If an exception is ignored by the program, the program will
terminate abnormally and produce an appropriate message.
•
The message includes a call
stack trace that indicates the
line on which the exception
occurred.
•
The call stack trace also shows the method call trail that lead to
the attempted execution of the offending line. Remember, an
exception is an object.
 The getMessage method returns a string explaining why
the exception was thrown
The printStackTrace method prints the call stack trace
The try Statement
•
To process an exception when it occurs, the line that
throws the exception is executed within a try block
•
A try block is followed by one or more catch
clauses, which contain code to process an exception
•
Each catch clause has an associated exception type
and is called an exception handler
•
When an exception occurs, processing continues at
the first catch clause that matches the “exception
type”
Explanation of try block
•
Java is instructed to try to execute a block of statements.
•
If the statements in the block execute without producing an exception, the catch
block is ignored, and execution continues beneath the catch block.
•
However, if an exception is produced, we can specify that the catch block is to
execute by stating the class of exception that we wish to catch.
•
Basic form of try-catch block -
try
{
. . .
//a series of statements to be executed
}
catch (someException e)
{
. . . // code to handle the exception
}
Exceptions
import java.awt.*;
import java.applet.*;
public class TrivialApplet extends Applet
{
//------------------------------// Deliberately divides by
// zero to produce an exception.
//------------------------------public void init()
{
int numerator = 10;
int denominator = 0;
System.out.println ("This text will be printed.");
try
{
System.out.println (numerator / denominator);
}
catch (ArithmeticException e)
{
System.out.println ("This text will now be printed.");
}
}
}
Another Example
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class ExceptionDemo1 extends Applet implements ActionListener
{
TextField stringField = new TextField(20), resultField = new TextField(20);
Label resultLabel = new Label ("Answer:"), stringLabel = new Label("Type an integer:");
float number;
public void init()
{
resultField.setEditable(false);
add(stringLabel);
add(stringField);
stringField.addActionListener(this);
add(resultLabel);
add(resultField);
}
public void actionPerformed(ActionEvent event)
{
try
{
number = Float.parseFloat(stringField.getText().trim());
resultField.setText("Doubled value = " + (2 * number));
}
catch (NumberFormatException e)
{
resultField.setText("Error in number - retype");
}
}
}
Exceptions
• As mentioned earlier, when a try block produces an exception, its execution
is terminated - it is abandoned.
• A consequence of this is that any variables declared within the try block
become inaccessible and cannot be used in the catch block, even if the catch
block is in the same method.
• This can be a problem if we want to use those variables to produce a
specific error message detailing what caused the problem.
• For example, you might want to display a wrongly formatted string if it was
not able to be converted to an integer.
• A simple solution - any variable that is required inside the catch block must
be declared outside the try block.
Examples
try
{
String s = tf.getText().trim();
int x = Integer.parseInt(s);
}
catch (NumberFormatException e)
{
. . . // String s and int x not available here
}
String s = tf.getText().trim();
int x = 0; //initialized to 0 because of Java’s annoying warning message
try
{
x = Integer.parseInt(s);
}
catch (NumberFormatException e)
{
// string s is available here since declared outside try
System.out.println(s + “ input: “ + e.toString());
}
System.out.println("Number = " + x);
Note: 1500
entered into tf produces: Number = 1500
1.5
produces: “1.5 input: java.lang.NumberFormatException: For input string: "1.5”
Number = 0 //produced by System.out.println() that appears after the catch
xyz
produces: “xyz input: java.lang.NumberFormatException: For input string: "xyz”
Number = 0 //produced by System.out.println() that appears after the catch
The search for a Catcher
•
What if the program doesn’t catch a thrown exception?
•
Actually, the rules for this depend on the class of exception.
•
The basic principle is based on the fact that all programs, for the most part, are made
up of methods.
•
Thus, at run-time, an initial method is invoked, which itself invokes other methods,
which in turn invoke others, etc…
•
Imagine that methodA() invokes methodB() which invokes methodC().
•
If an exception occurs in methodC(), the search for an appropriate catch begins
in methodC().
•
If one is not found, the search moves to methodB(), and then to methodA(),
etc.
•
If the top-level method does not provide a catch, an exception message is displayed
and the program terminates abnormally (for an applet, it will continue to run and its
results will be unreliable).
Still Another Example
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class AnotherExceptionExample extends Applet implements ActionListener
{
TextField numField = new TextField(15), denomField = new TextField(15), resultField = new
TextField(15);
Label resultLabel = new Label ("Answer:"), denomLabel = new Label("Enter the denominator"), numLabel =
new Label("Enter the numerator");
public void init()
{
add(numLabel);
add(denomLabel);
add(resultLabel);
}
add(numField);
add(denomField);
add(resultField);
numField.addActionListener(this);
denomField.addActionListener(this);
resultField.setEditable(false);
public void actionPerformed(ActionEvent event)
{
try
{
int numerator = Integer.parseInt(numField.getText().trim());
int denominator = Integer.parseInt(denomField.getText().trim());
resultField.setText("" + numerator/denominator);
}
catch (NumberFormatException e1)
{
resultField.setText("Error in number - ");
}
catch (ArithmeticException e2)
{
resultField.setText("Divide by Zero");
}
//continue here afterwards
}
}
Finally, finally
•
The finally clause is used for activities that should be performed whether or not an exception was
thrown and caught.
•
Syntax:
finally
{
//cleanup code
}
•
A try block can have at most one finally clause, and it must appear immediately after the last
catch clause.
•
The block of a finally clause is guaranteed to be executed, no matter how controls leaves its try
block.
•
If none of the catch clauses is executed, the finally clause is executed after the try block.
•
If one of the catch clauses is executed, the finally clause is executed after completion of the
catch.
•
The finally clause is executed even if the try or catch portions contain break or return
statements.
•
A finally clause is generally used for cleanup purposes. (For example, emptying out TextFields to get
ready for the next user input.