Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Exceptions to the programming rules, Part 2

Incorporate Java's throw-object/catch-object exception-handling technique into your Java programs

  • Print
  • Feedback

Page 7 of 8

'catch' '(' exceptionIdentifier objectIdentifier ')'
'{'
   statement ...
'}'


The catch clause begins with keyword catch and a parameter list consisting of one parameter. objectIdentifier names the parameter, and exceptionIdentifier serves as the parameter's type -- which must be Throwable or a subclass. The catch clause concludes with a block of exception-handling statements that allow a program/library to recover from an exception.

When an exception object is thrown, the JVM searches backwards through the method-call stack for the first catch clause whose exceptionIdentifier either exactly matches or is the supertype of the exception object's type. Upon finding a match, the JVM calls the catch clause and passes the exception object's reference to that clause, as part of the call. At that point, the exception object is caught. The following code fragment demonstrates a catch clause:

catch (FileNotFoundException exc)
{
   System.out.println (exc.getMessage ());
}


The code fragment's catch clause catches FileNotFoundException objects. When the JVM passes execution to catch (FileNotFoundException exc), that clause calls the exception object's getMessage() method to retrieve a String object that describes the exception. That object's contents subsequently print.

A catch clause cannot appear alone in source code. Instead, source code must express a catch clause in association with a try block. A try block has the following syntax:

  • Print
  • Feedback

Resources