Saturday, September 7, 2013

Three rules for effective exception handling in java

If we are dealing with exceptions basically it has to tell you the following things.

1. What went wrong ?
2. Where did it go wrong ?
3. Why did it go wrong ?

so, to address above points we need follow 3 golden rules of exception handling.

1.  Be specific on exception type  -> It should tell what went wrong, ex: file not found, connection not found

2. Throw early - > ex: if you are passing null file name to FileInputStream it throws null pointer exception, but this is not sufficient to the user, instead check whether it is null or not ,then throw an exception that "File name can't be empty".

3. Catch late- > Catch where you want to show it the user immediately. Don't log and catch at the API level or lower level, instead throw from api or lower level and catch at the UI layer or at the top layer.


https://today.java.net/pub/a/today/2003/12/04/exceptions.html




No comments:

Post a Comment