Declaring Methods That Might Throw Exceptions

In previous examples, you learned how to deal with methods (by protecting code and catching any exceptions that occur) that might throw exceptions. The Java compiler checks to make sure that you've somehow dealt with a method's exceptions—but how did it know which exceptions to tell you about in the first place?

The answer is that the original method indicated in its signature contains the exceptions that it might possibly throw. You can use this mechanism in your own methods—in fact, it's good style to do so to make sure your classes'other users are alerted to the errors your methods may come across.

To indicate that a method may possibly throw an exception, you use a special clause in the method ...

Get Sams Teach Yourself Java 2 in 21 Days, Second 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.