Online Software Educational Training - IT Tutorials - Online Education Training for Computer Software


Home

JAVA PROGRAMMING

Using try and catch

The try Block 

The first step in constructing an exception handler is to enclose the statements that might throw an exception within a try block. In general, a try block looks like this: 
try {
Java statements
}

The segment of code labeled Java statements is composed of one or more legal Java statements that could throw an exception. 

The catch block 

As you learned on the above, the try statement defines the scope of its associated exception handlers. You associate exception handlers with a try statement by providing one or more catch blocks directly after the try block: 

try {
. . . 
} catch ( . . . ) {
. . . 
} catch ( . . . ) {
. . . 
} . . . 

There can be no intervening code between the end of the try statement and the beginning of the first catch statement. The general form of Java's catch statement is: 
catch (SomeThrowableObject variableName) {
Java statements
}

As you can see, the catch statement requires a single formal argument. The argument to the catch statement looks like an argument declaration for a method. The argument type, SomeThrowableObject, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class defined in the java.lang package. When Java programs throw an exception they are really just throwing an object, and only objects that derive from Throwable can be thrown. You'll learn more about throwing exceptions in How to Throw Exceptions. 
variableName is the name by which the handler can refer to the exception caught by the handler. For example, the exception handlers for the writeList method (shown later) each call the exception's getMessage method using the exception's declared name e: 

e.getMessage()

You access the instance variables and methods of exceptions in the same manner that you access the instance variables and methods of other objects. getMessage is a method provided by the Throwable class that prints additional information about the error that occurred. The Throwable class also implements two methods for filling in and printing the contents of the execution stack when the exception occurred. Subclasses of Throwable can add other methods or instance variables. To find out what methods an exception implements, check its class definition and definitions for any of its ancestor classes. 
The catch block contains a series of legal Java statements. These statements are executed if and when the exception handler is invoked. The runtime system invokes the exception handler when the handler is the first one in the call stack whose type matches that of the exception thrown.

An example code using try and catch block






Previous

Next