home account info subscribe login search My ITKnowledge FAQ/help site map contact us


 
Brief Full
 Advanced
      Search
 Search Tips
To access the contents, click the chapter and section titles.

Sams Teach Yourself Visual J++ 6 in 21 Days
(Publisher: Macmillan Computer Publishing)
Author(s): Rick Leinecker
ISBN: 0672313510
Publication Date: 11/01/98

Bookmark It

Search this book:
 
Previous Table of Contents Next


Throwing Exceptions

Before an exception can be caught, it must be thrown. Exceptions can be thrown by any Java code: your own code, code in the packages that come with the Java development environment, and code in packages written by others. Even the Java runtime system can throw exceptions that your programs must catch.

When an exception is thrown, the Java runtime system receives a signal that an error has been generated. Exceptions are thrown to flag errors, which is something you would do in your own programs to notify the system that an error has occurred. As soon as an exception is thrown, the runtime system searches for the matching catch clause to handle it.

Exceptions are thrown using the following Java syntax:

throw new AnyExceptionObject():

Regardless of what code raises an exception, it’s always done via the throw statement. throw takes a single argument: a throwable object. Throwable objects are instances of any subclass of the Throwable class defined in the java.lang package. In the preceding example, you instantiated a throwable object:

new AnyExceptionObject()// instantiate throwable object

If you attempt to throw an object that isn’t throwable, the compiler outputs an error message and refuses to complete the compilation process. Most exception objects you’ll encounter are derived from the Exception class, the RuntimeException class, or the Error class. Each of these classes is a subclass of Throwable (java.lang.Throwable), and therefore produces objects (or is extended by other classes) that are considered throwable.

Consider for a moment the following method declaration:

public static int myDivide( int x, int y)
  throws ArithmeticException()
{
    if( y == 0)
        throw new ArithmeticException();
    else return( x / y);
}

In the method signature, you declare this method as being capable of throwing the ArithmeticException:

throws ArithmeticException

The Java language requires that methods either catch or declare all nonruntime exceptions they can throw. With the preceding line, you declare that your myDivide() method throws the ArithmeticException, satisfying this requirement.

In cases in which you want to define your own methods, you simply create a new class that is a subclass of Exception. Here is the same program, but using a custom exception:

class MyOwnException extends Exception
{

    public static int myDivide(int x, int y) throws MyOwnException
    {
        if( y == 0) throw new MyOwnException();
        else return( x / y);
    }
}

However, throwing exceptions is only half the battle. To write effective Java programs, you must be able to catch exceptions as well.

Catching Exceptions

When an exception is thrown, the Java runtime system immediately stops the current flow of program execution and looks for an exception handler to catch it. Searching backward through the call stack, a corresponding handler is started with the method where the error occurred.

The search continues down the call stack until a method containing an appropriate exception handler is found. The first handler encountered that has the same type as the thrown object is the one chosen to deal with the exception.

If the exception travels all the way down the call stack with no handler catching it, the program aborts execution. Typically, an error message is output to the terminal display in such cases. This, of course, assumes that the exception is a runtime exception that can’t be seen by the compiler.

Dividing a number by a variable that happens to be zero, accessing an array element using an index variable that is beyond the legal range, and accessing null objects and similar dynamic activities will all produce runtime exceptions that aren’t recognized at compile time. As a result, the compiler can’t force you to catch such exceptions, because it doesn’t even realize that they exist. And in cases in which a runtime exception propagates to the bottom of the call stack, your program will be aborted.

To catch an exception, you must write an exception handler using the try-catch clause. For instance, suppose you wanted to use the original myDivide() method created earlier. To catch the exception that might result, you’d write the following try-catch clause:

try
{
    int y = myDivide( 10, 0):
}
catch( ArithmeticException e)
{
    System.out.println( "Whoops – there it is!");
}


Previous Table of Contents Next


Products |  Contact Us |  About Us |  Privacy  |  Ad Info  |  Home

Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc.
All rights reserved. Reproduction whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement.