7.3. Dealing with Exceptions

As I discussed in the previous sections, if your code can throw exceptions other than those of type Error or type RuntimeException (you can assume that I generally include the subclasses when I talk about Error and RuntimeException exceptions), you must do something about it. Whenever you write code that can throw an exception, you have a choice. You can supply code within the method to deal with any exception that is thrown, or you can essentially ignore it by enabling the method containing the exception-throwing code to pass it on to the code that called the method.

Let's first see how you can pass an exception on.

7.3.1. Specifying the Exceptions a Method Can Throw

Suppose you have a method that can throw an exception that is neither a subclass of RuntimeException nor of Error. This could be an exception of type IOException, for example, which can be thrown if your method involves some file input or output operations. If the exception isn't caught and disposed of in the method, you must at least declare that the exception can be thrown. But how do you do that?

You do it simply by adding a throws clause in the definition of the method. Suppose you write a method that uses the methods from classes that support input/output that are defined in the package java.io. You'll see in the chapters devoted to I/O operations that some of these can throw exceptions represented by objects of classes IOException and FileNotFoundException. Neither of these is ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition 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.