When to use throws in a Java method declaration?

jbranchaud picture jbranchaud · Dec 8, 2010 · Viewed 124.9k times · Source

So I thought I had a good basic understanding of exception-handling in Java, but I was recently reading some code that gave me some confusion and doubts. My main doubt that I want to address here is when should a person use throws in a Java method declaration like the following:

    public void method() throws SomeException
    {
         // method body here
    }

From reading some similar posts I gather that throws is used as a sort of declaration that SomeException could be thrown during the execution of the method.

My confusion comes from some code that looked like this:

     public void method() throws IOException
     {
          try
          {
               BufferedReader br = new BufferedReader(new FileReader("file.txt"));
          }
          catch(IOException e)
          {
               System.out.println(e.getMessage());
          }
     }

Is there any reason that you would want to use a throws in this example? It seems that if you are just doing basic exception-handling of something like an IOException that you would simply need the try/catch block and that's it.

Answer

hvgotcodes picture hvgotcodes · Dec 8, 2010

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?