When to use throws in a Java method declaration? When to use throws in a Java method declaration? java java

When to use throws in a Java method declaration?


If you are catching an exception type, you do not need to throw it, unless you are going to rethrow it. In the example you post, the developer should have done one or another, not both.

Typically, if you are not going to do anything with the exception, you should not catch it.

The most dangerous thing you can do is catch an exception and not do anything with it.

A good discussion of when it is appropriate to throw exceptions is here

When to throw an exception?


You only need to include a throws clause on a method if the method throws a checked exception. If the method throws a runtime exception then there is no need to do so.

See here for some background on checked vs unchecked exceptions: http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html

If the method catches the exception and deals with it internally (as in your second example) then there is no need to include a throws clause.


The code that you looked at is not ideal. You should either:

  1. Catch the exception and handle it;in which case the throws isunnecesary.

  2. Remove the try/catch; in which casethe Exception will be handled by acalling method.

  3. Catch the exception, possiblyperform some action and then rethrowthe exception (not just the message)