Rethrow exception in java

18,229

Solution 1

You are right. Second version is better. Moreover the first version does not make any sense. It does the same except the stack trace of the exception will be "wrong".

There are the following reasons to "re-throw" exceptions:

  1. If you have something to do before.
  2. If you catch exception of one type and throw exception of other type:

example:

try {
   // do something
} catch (IOException ioe) {
    throw new IllegalStateException(ioe);
}

Solution 2

In the example given, re-throwing the Exception serves no purpose.

Doing this can be useful if the method that catches and then re-throws the exception needs to take some additional action upon seeing the Exception, and also desires that the Exception is propagated to the caller, so that the caller can see the Exception and also take some action.

Solution 3

I would only catch/rethrow an exception (instead of just throwing it) if I wanted to do something else in the catch block - for example, write a logging statement before rethrowing.

Solution 4

In addition to wanting to do something with the exception before exiting - like logging, the other time you would do something like that is if you want to wrap it as a different exception, like:

try {
    FileReader reader = new FileReader("java.pdf");
} catch (FileNotFoundException ex) {
    throw new ServletException(ex);
}

Solution 5

The question is why you think you need to rethrow the exception. Did Eclipse suggest surrounding with try-catch? In practice we rarely rethrow the same exception, but very often catch one and throw another that wraps the first one, especially if the wrapper exception is unchecked. This happens whenever you have calls declaring checked exceptions, but the method you write those calls in doesn't declare those exceptions:

public int findId(String name) {
  try {
    return db.select("select id from person where name=?", name);
  } catch (SQLException e) {
    throw new RuntimeException(e);
  }
}
Share:
18,229
MinhHoang
Author by

MinhHoang

Updated on June 24, 2022

Comments

  • MinhHoang
    MinhHoang almost 2 years

    I have a very simple question about re-throwing exception in Java.

    Here is the code snippet:

    public static void main(String[] args) throws FileNotFoundException {
        try {
            FileReader reader = new FileReader("java.pdf");
        } catch (FileNotFoundException ex) {
            throw ex;
        }
    }
    
    public static void main(String[] args) throws FileNotFoundException {        
            FileReader reader = new FileReader("java.pdf");        
    }
    

    Why do we need to re-throw ex in the first version while the second version looks more elegant? What might be the benefits and which version is preferred over the other?

  • MinhHoang
    MinhHoang over 11 years
    So it is more often that we do rethrow unchecked exception as wrapper instead of checked exception, isn't it?
  • Dev
    Dev over 11 years
    @AlexR Agreed the first way looks odd. The stacktrace will not be 'wrong' though. The stacktrace is filled in when the exception is constructed not when it thrown. This can be seen in the source code for java.lang.Throwable
  • hotshot309
    hotshot309 over 11 years
    Good point. Just keep in mind what is "checked" and "unchecked" in the context of your application. Checked Exceptions should account for expected occasional anomalies that the application should handle. Unchecked Exceptions are for rare, fatal faults that cannot be recovered from or necessarily even anticipated. When rethrowing, I think that "unchecked" things should be wrapped in unchecked Exceptions, and "checked" things be wrapped in checked Exceptions. See Oracle's "Effective Exceptions."
  • Marko Topolnik
    Marko Topolnik over 11 years
    @hotshot309 That's not quite it: every exception that means aborting the current unit of work should be unchecked and travel upwards into the common exception barrier. Only exceptions that can be recovered from within the unit of work, basically with an alternative processing strategy, are candidate checked exceptions and could also be unchecked, up to the implementor to decide. BTW you wish unrecoverable faults were rare; they are the norm, in fact. Of all exceptions thrown, 90% or more are unrecoverable.
  • sleske
    sleske over 10 years
    However, typically "take some action upon seeing the exception" is better handled in a finally{} block.
  • pb2q
    pb2q over 10 years
    @sleske: I disagree. finally is always executed. So, taking @smcg's example of logging the exception: I only want that log entry in the catch, but not when the Exception doesn't happen. If it's in the finally I'll always get the log entry even when no Exception is thrown
  • Julien
    Julien about 7 years
    agreed, stack trace will be the same when you simply re-throw the Exception you just caught