Monday, May 26, 2008

All About Java Exceptions

Common Java wisdom gives us a few general principles about how to work with exceptions:

1. Don’t use exceptions for flow control and expected business situations, but only for exceptional situations
2. Use unchecked exceptions for programming errors, bugs, situations where the application or the current operation cannot expect to recover from.
3. Use checked exceptions for situations where the caller is expected to be able to make a full or partial recovery after the failure

If we keep the function return type as


public boolean doSomeWork()
{
if(success)
return true;
else
return false;
...
}


two probs
1) Caller will have to check the return value : if he doesnt he may continue with wrong assumption
2) The caller doesn’t have enough information to see what went wrong

With this kind of solution we are back to the way C programs were written... but remember this is java

Another way is...

public class SomeException extends RuntimeException
{
...
}
public boolean doSomeWork()
{
if(success)
return true;
else
throw new SomeException();
...
}


You may have to do some documentation for the new exception class. Which is a disadvantage if you are LAZY ;).
Else the advantages are
* If the client code fails to treat the exception at least the program doesn’t continue on a wrong path.
* We can send more information about the failure context in the exception class through the exception type and the exception instance content.
Disadvantages
* The client code programmer is not automatically warned to treat the exception


One more way is ...

public class SomeException extends Exception
{
...
}
public boolean doSomeWork() throws SomeException
{
if(success)
return true;
else
throw new SomeException();
...
}

Client code will use try / catch block

How can you catch multiple exceptions in java ??

Statement stmt = null;
try {
// do stuff that uses Statement instance
} catch (SQLException e) {
// handle state
log.error("Bad database", e);
} catch (NullPointerException e) {
// handle state
log.error("Bad parameter", e);
} catch (Exception e) {
// handle state
log.error("Bad luck", e);
} finally {
try {
stmt.close();
} catch (Exception ex) {}
}


Summary
Rule of thumb: Use Checked Exceptions for recoverable conditions and Runtime Exceptions for programming errors.
Checked exceptions are great in theory, but in practice lots of developers use them poorly and then the rest of us are left to clean up their mess.
checked exceptions are domain exceptions.

Links
http://truecode.blogspot.com/2008/01/bypassing-java-checked-exception.html
http://dev2dev.bea.com/pub/a/2006/11/effective-exceptions.html
http://dev2dev.bea.com/pub/a/2007/06/exception-advice.html
http://www.csd.uoc.gr/~andreou/

No comments: