Checked Exceptions

Checked exceptions are exceptions that the designers of Java feel that your programs absolutely must provide for, one way or another. Whenever you code a statement that could throw a checked exception, your program must do one of two things:

check.png Catch the exception by placing the statement within a try statement that has a catch block for the exception.

check.png Specify a throws clause on the method that contains the statement to indicate that your method doesn’t want to handle the exception, so it’s passing the exception up the line.

tip.eps Be careful not to confuse throw with throws. The throws keyword is used on a method to indicate that the method doesn’t catch a particular checked exception but rather throws it up to the calling routine. The throw statement, on the other hand, is an executable statement that actually throws an exception. For more information, see throw Statement.

This is the “catch-or-throw” rule. In short, any method that includes a statement that might throw a checked exception must acknowledge that it knows the exception might be thrown. The method does this by handling it directly or by passing the exception up to its caller.

For example, a method that uses ...

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.