Rethrowing of exception in java has improved starting from Java 7. We can now specify more specific exceptions using throws keyword.
Before java 7:
1 2 3 4 5 6 7 8 9 10 11 12 |
public void someMethod(String testStr) throws Exception { try { if (testStr.equals("SomeThing")) { throw new UserException1(); } else { throw new UserException2(); } } catch (Exception e) { //Do some processing.. throw e; } } |
In the above method, the try block can throw either UserException1 or UserException2, this exceptions are caught in the catch block, here we add some statements and then throw a new exception.
Now if you wanted to specify the 2 exceptions in the Throws clause , earlier to java 7 this was not possible, hence you had to throw a new exception. This meant that the original exception was overridden by a new exception.
To handle this starting from java 7, you can Rethrow Exceptions with More inclusive Type Checking.
1 2 3 4 5 6 7 8 9 10 11 12 |
public void someMethod(String testStr) throws UserException1, UserException2{ try { if (testStr.equals("SomeThing")) { throw new UserException1(); } else { throw new UserException2(); } } catch (Exception e) { //Do some processing.. throw e; } } |
Using this you can now rethrow the original exception, that may be helpful for the end consumer of the method.