What happens if a method throws an exception that was not specified in the method declaration with "throws"

bluehallu picture bluehallu · Feb 3, 2011 · Viewed 38.8k times · Source

I've never used the "throws" clause, and today a mate told me that I had to specify in the method declaration which exceptions the method may throw. However, I've been using exceptions without problems without doing it, so, why is it needed if, in fact, it's needed?

Answer

Andreas Dolk picture Andreas Dolk · Feb 3, 2011

Java has two different types of exceptions: checked Exceptions and unchecked Exceptions.

Unchecked exceptions are subclasses of RuntimeException and you don't have to add a throws declaration. All other exceptions have to be handled in the method body, either with a try/catch statement or with a throws declaration.

Example for unchecked exceptions: IllegalArgumentException that is used sometimes to notify, that a method has been called with illegal arguments. No throws needed.

Example for checked exceptions: IOException that some methods from the java.io package might throw. Either use a try/catch or add throws IOException to the method declaration and delegate exception handling to the method caller.