Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
You associate exception handlers with atry
block by providing one or morecatch
blocks directly after thetry
block. No code can be between the end of thetry
block and the beginning of the firstcatch
block:Eachtry { ... } catch (ExceptionType name) { ... } catch (ExceptionType name) { ... } ...catch
block is an exception handler and handles the type of exception indicated by its argument. The argument type,ExceptionType
, declares the type of exception that the handler can handle and must be the name of a class that inherits from theThrowable
class. The handler can refer to the exception withname
.The
catch
block contains code that is 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 whoseExceptionType
matches the type of the exception thrown. The system considers it a match if the thrown object can legally be assigned to the exception handler's argument.Here are two exception handlers for the
writeList
method one for two types of checked exceptions that can be thrown within the try statement:Both handlers print an error message. The second handler does nothing else. By catching anytry { ... } catch (FileNotFoundException e) { System.err.println("FileNotFoundException: " + e.getMessage()); throw new SampleException(e); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); }IOException
that's not caught by the first handler, it allows the program to continue executing.The first handler, in addition to printing a message, throws a user-defined exception. (Throwing exceptions is covered in detail a little later in the section How to Throw Exceptions.) In this example, the
FileNotFoundException
, when caught, causes a user-defined exception calledSampleException
to be thrown. You might want to do this if you want your program to handle a this exception in this situation in a specific way.Exception handlers can do more than just print error messages or halt the program. They can do error recovery, prompt the user to make a decision, or propagate the error up to a higher-level handler using chained exceptions, as described in the section Chained Exceptions.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.