Throwing Exceptions

Your method might not be the very best place to handle an exception. It might make more sense to let the exception pass through your method unhandled, and make some other guy deal with it. You can do that. But you have to say that that is what you're doing. You do so with the throws keyword. The following modified method will also compile and run:

public void someMethod () throws IOException {
       File f = new File("s");
       f.getCanonicalFile();
}

Do not declare that your method throws unchecked exceptions that inherit from Runtime-Exception. Do not write the following:

void do(int i) throws NullPointerException
     //BAD DOG! NO!
{
     //blah blah blah
}

Why should you never do that? Sometimes the truth is tough. If you are that worried ...

Get Java Garage 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.