When to use throws in a Java method declaration?

127,114

Solution 1

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?

Solution 2

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.

Solution 3

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)

Solution 4

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.

Solution 5

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());
   }

}

Share:
127,114

Related videos on Youtube

jbranchaud
Author by

jbranchaud

I love writing code, photographing things, and shooting pool. I created captionss - Sensible CSS Image Captions I am a co-founder of Beer and Code in Lincoln, NE. I am on GitHub and Flickr. Feel free to contact me via email or twitter.

Updated on December 01, 2020

Comments

  • jbranchaud
    jbranchaud over 3 years

    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.

  • Cody
    Cody about 10 years
    Should unchecked exceptions also be declared in the method signature with a 'throws', or is it practice to only use 'throws' for checked exceptions?
  • Brent Bradburn
    Brent Bradburn almost 6 years
    The compiler does a surprisingly sophisticated static analysis to decide whether or not the throws is required.
  • Brent Bradburn
    Brent Bradburn almost 6 years
    This answer does not directly address the central aspect of the question: The use of the throws keyword.
  • Manoj
    Manoj over 5 years
    @hvgotcodes What happens if I catch an exception and do nothing?
  • hvgotcodes
    hvgotcodes over 5 years
    @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.