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 5 of 8

'throw' expression ';'


The throw statement begins with keyword throw, continues with an expression that evaluates to an object reference, and terminates with a semicolon character. expression's type must be Throwable or a subclass type. Otherwise, the compiler reports an error. The following code fragment demonstrates creating, initializing, and throwing an exception object of type FileNotFoundException:

throw new FileNotFoundException ("Unable to open file " + filename); // Assume previous String filename; declaration. 
Programs typically use throw to throw checked exception objects, as the previous code fragment demonstrates. In contrast, libraries often use throw to throw unchecked exception objects. Library methods throw unchecked exception objects because guaranteeing that a calling method will always pass valid argument values to those methods proves impossible. For example, consider the following code fragment:

static void printReport (Employee e)
{
   if (e == null)
       throw new NullPointerException ();
   // ... other code ...
}


The printReport(Employee e) library method checks Employee argument e's contents. If e contains a null reference, printReport(Employee e) creates and throws a NullPointerException unchecked exception object. Execution immediately leaves, and does not return to, the printReport(Employee e) method.

Caution
Do not attempt to throw objects from any class apart from Throwable or a Throwable subclass. Otherwise, the compiler reports an error. The compiler also reports an error when a method attempts to throw a checked exception object but does not list that object's class name in the method's throws clause.


When a method throws a checked exception object, the compiler forces that method to list the object's class or superclass in the method's throws clause. That clause appends to a method's signature and has the following syntax:

  • Print
  • Feedback

Resources