When to use throws in a Java method declaration?
Asked Answered
D

7

93

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.

Deandreadeane answered 8/12, 2010 at 21:18 Comment(0)
F
87

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?

Fagin answered 8/12, 2010 at 21:26 Comment(4)
Should unchecked exceptions also be declared in the method signature with a 'throws', or is it practice to only use 'throws' for checked exceptions?Illustrator
This answer does not directly address the central aspect of the question: The use of the throws keyword.Zora
@Fagin What happens if I catch an exception and do nothing?Cocky
@manoj you risk things breaking and not being able to figure it out because crucial information is lost. There are times (not necessarily java) where it is ok to catch an exception and do nothing, but those should be documented. For example, in javascript you can try to invoke functionality which might not exist depending on a browser. That's not necessarily an error that needs attention.Fagin
C
27

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.

Cowell answered 8/12, 2010 at 21:32 Comment(0)
S
9

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

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

  2. Remove the try/catch; in which case the Exception will be handled by a calling method.

  3. Catch the exception, possibly perform some action and then rethrow the exception (not just the message)

Spires answered 8/12, 2010 at 21:32 Comment(0)
T
2

You're correct, in that example the throws is superfluous. It's possible that it was left there from some previous implementation - perhaps the exception was originally thrown instead of caught in the catch block.

Tjirebon answered 8/12, 2010 at 21:29 Comment(0)
W
2

The code you posted is wrong, it should throw an Exception if is catching a specific exception in order to handler IOException but throwing not catched exceptions.

Something like:

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

or

public void method() {
   try {
           BufferedReader br = new BufferedReader(new FileReader("file.txt"));
   } catch(IOException e) {
           System.out.println("Catching IOException");
           System.out.println(e.getMessage());
   } catch(Exception e) {
           System.out.println("Catching any other Exceptions like NullPontException, FileNotFoundExceptioon, etc.");
           System.out.println(e.getMessage());
   }
}
Womankind answered 18/10, 2012 at 23:19 Comment(0)
V
1

In the example you gave, the method will never throw an IOException, therefore the declaration is wrong (but valid). My guess is that the original method threw the IOException, but it was then updated to handle the exception within but the declaration was not changed.

Viguerie answered 8/12, 2010 at 21:31 Comment(0)
C
1

This is not an answer, but a comment, but I could not write a comment with a formatted code, so here is the comment.

Lets say there is

public static void main(String[] args) {
  try {
    // do nothing or throw a RuntimeException
    throw new RuntimeException("test");
  } catch (Exception e) {
    System.out.println(e.getMessage());
    throw e;
  }
}

The output is

test
Exception in thread "main" java.lang.RuntimeException: test
    at MyClass.main(MyClass.java:10)

That method does not declare any "throws" Exceptions, but throws them! The trick is that the thrown exceptions are RuntimeExceptions (unchecked) that are not needed to be declared on the method. It is a bit misleading for the reader of the method, since all she sees is a "throw e;" statement but no declaration of the throws exception

Now, if we have

public static void main(String[] args) throws Exception {
  try {
    throw new Exception("test");
  } catch (Exception e) {
    System.out.println(e.getMessage());
    throw e;
  }
}

We MUST declare the "throws" exceptions in the method otherwise we get a compiler error.

Cloison answered 30/11, 2017 at 15:51 Comment(1)
The compiler does a surprisingly sophisticated static analysis to decide whether or not the throws is required.Zora

© 2022 - 2024 — McMap. All rights reserved.