Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rethrow exception in java

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?

like image 550
MinhHoang Avatar asked Aug 15 '12 15:08

MinhHoang


People also ask

What is Rethrow exception in Java?

If a catch block cannot handle the particular exception it has caught, we can rethrow the exception. The rethrow expression causes the originally thrown object to be rethrown.

What happens when you Rethrow exception?

An exception can be rethrown in a catch block. This action will cause the exception to be passed to the calling method. If the rethrow operation occurs in the main method then the exception is passed to the JVM and displayed on the console.

Is it good practice to Rethrow exception?

Catching and throwing exceptions is an overhead and is useless (except if you do something with it before re-throw, i.e. log it), so the programmer will actually be confused, thinking there is a bug and not understanding what the original intent was.

What is Rethrow?

rethrow (plural rethrows) (programming) The act of throwing an exception again.


1 Answers

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);
  }
}
like image 63
Marko Topolnik Avatar answered Oct 14 '22 17:10

Marko Topolnik