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?
Share
Java has two different types of exceptions: checked Exceptions and unchecked Exceptions.
Unchecked exceptions are subclasses of
RuntimeExceptionand 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:
IllegalArgumentExceptionthat is used sometimes to notify, that a method has been called with illegal arguments. No throws needed.Example for checked exceptions:
IOExceptionthat some methods from thejava.iopackage might throw. Either use a try/catch or addthrows IOExceptionto the method declaration and delegate exception handling to the method caller.