Tutorial :use of rethrowing checked/unchecked exceptions?



Question:

What is the use of rethrowing checked and unchecked exceptions?


Solution:1

If you want to execute some code when a problem happens without hiding the problem.

For example, let's say you want to rollback changes if an exception occurs while writing to a database:

try {      writeToDatabase();  } catch(Exception ex) {      rollbackChanges();  }  

If you use this code, the calling function will never find out that an exception occurred.

Instead, you should write

try {      writeToDatabase();  } catch(Exception ex) {      rollbackChanges();      throw ex;  }  


Solution:2

To be somewhat blunt: to use exception handling.

Consider this, before exceptions (or, before a developer understands how to properly use exception handling) programmers would return error codes like -1 or null if something 'went wrong'. With that in mind, how would you tell something several methods back that it failed (eg: some low level IO method in a large API failed)? You could either string a lot of return nulls/ or -1's together, or just throw an exception so that it migrates back up to somewhere where it should be caught, even the JVM itself if need be as this exception might something you cannot recover from.

So basically, you would rethrow an exception if you are unable to write catch logic that can truly recover from the thrown exception. This is often the case in Java because Java forces you to catch almost all of its Exceptions since most everything is a checked exception.

As for rethrowing checked vs unchecked... Often times I will throw a new unchecked exception (RuntimeExpcetion) from inside a checked exception back up to the container when doing J2EE applications. The container has a default way of handling exceptions and showing the user a default error page. This comes from the Aspect Oriented paradigm. I also wrote about how to do this here.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »