|
Definition
An unusual condition that prevents the normal sequence of
instructions from going forward (from Bruce Eckel, "Thinking in Java")
.
What Happens in Java
-
If an exception occurs, Java immediately halts the normal program
execution.
-
It then generates an object of type Throwable, usually referred to
as an "exception object", though technically, the Exception class is a
subclass of Throwable.
-
It then retraces its steps back up the call stack (the methods
who's operations are pending because they were in the middle of
making a call to another method when the exception occurred). The
Java virtual machine is looking for code that is capable of handling the
exception. This is called "throwing the
exception".
-
If it finds the proper exception handling code (a "catch" clause,
see below) then it will execute it, handing it the exception object,
otherwise it will halt the program completely.
Classes Involved with Exceptions
These classes hold information about the nature of the exception.
- "Throwable", the parent class of all exception
related classes.
- "Error" is the other subclass of Throwable, but
these are reserved for catastrophic errors that can't be normally be
handled in a user's program.
- "Exception" class is for errors that can be
generally handled.
Exception Related Keywords
- "throws
[Throwable class]" keyword: Used in a method's signature to mean
that the method may generate an exception of the specified
type. If a method is declared as throwing a particular
class of exceptions, then any other method that calls it must either
have a
try-catch clause to handle that exception or must be declared to
throw that exception (or its superclass) itself.
- "try" keyword: Used to denote
the beginning of a curly-brace enclosed block of code within which an
exception might be thrown.
- "catch" keyword:
immediately follows the try block and denotes the curly-brace enclosed
block of code that will execute when the specified exception (in the
following parantheses) is thrown inside the try block.
The syntax is designed to be enhance the conceptualization that the
catch "method" is executed when the particular exception is
thrown.
- "finally"
keyword: Denotes a block of code that will always execute, whether
or not an exception was thrown in the try block. The finally
block follows all the catch blocks.
finally blocks are very useful for providing "clean-up" code, such as closing file
or network connections, that must be executed no matter
what happens to the system.
- "throw" keyword: The system method that will
enables the programmer to throw an exception at that point in the
code. The exception will be caught by the nearest try-catch clause
that can catch that type of exception.
Syntax:
Catching an exception:
try {
[code that may generate an exception]
} catch( [Exception class]
variable_name) // optional
{ [code to
handle this type of
exception] }
catch( [Exception class] variable_name) //
optional
{ [another
code to handle this type of exception]
} .
. .
finally // optional
{
[code that is always executed, no matter what
happens] }
Throwing an exception
// Somewhere in the
code throw(new [Exception_class]);
Syntax Notes
- There must be a either catch or
finally blocks or both.
- "try" block:
- Must surround the call(s) that mey generate exceptions
- Or, the method that contains the exception generating method must
throw that exception or its superclass.
- When exception occurs, execution jumps directly to the first catch
block.
- "catch" block
- Declares a local variable that holds the exception
information. The type of the local variable
determines which catch statement is executed.
- Syntax looks and acts like a method -- treat it as if it was a
method that was called given a particular value for the input
parameter.
- Catch blocks are tried in order until a matching catch block is
found (i.e. declared catch type matches or is a superclass of the
generated exception.
- "finally" block
- Always executes, even if no exeception is generated.
- Used for "clean up".
- "throw([exception object])"
- Syntax used to explicitly throw an exception.
throw( new [Exception (sub)class]( [message string]));
- The exception thrown must be a (sub)class of the type the
method declares that it throws. E.g. if the method "throws
RuntimeException" then it can actually "throw(new
ArithmeticException("Math error"));
Examples
Catching an arithmetic exception:
int x, y, z;
try { z = x/y; } catch(ArithmeticException
e) { jLabel1.setText("Arthimetic Exception
caught: "+e.toString()); z =
0; } finally { jLabel2.setText("z =
"+z); }
Throwing an exception with a custom message:
try { // code where something might go
wrong throw(new Exception("Something went
wrong!")); // exception thrown here } catch(Exception
e) { System.out.println("The exception is:
"+ e); // exception caught here }
Declaring a method to throw an exception
public void myMethod(MyTypes myParam) throws
MyException { // code that somewhere, not in a
try-catch block, says something like throw( new
MyException()); }
Advanced Issues
Order of execution of catch blocks
Catch blocks are tested in the order the are written in the
code. Thus it is very important that a catch block that
catches a particular class of exceptions must not follow a catch
block that catches the superclass of that exception.
Using a finally block without a catch block
Using a finally block does not require that a catch block
exist. For instance, a try-finally clause inside a
loop's body can be used to always execute a particular piece of code
in a loop, even if the code in try block executes a "break" statement to
terminate the loop.
Using a finally block to override an break or return
statement
Since the finally block of a try-catch-finally clause is always
executed, even if a break or return statement is executed in the try
block, the finally block can actually override the request to break
or return. The finally block can decide not to break or
return or even change the return value by executing its own return
statement.
|