If-Else vs Throwing an Exception to handle errors
Note: In reading this post, please disregard for a moment the difference between an exception and an error. I mainly used the word error for convenience. Thank you.
Yesterday, I was given a tip by my team lead which I found nice and quite elegant to do so. Before, when I'm trying to catch an error I'm always tempted to do the following
[code Language="Java"]
if (true){
//doSomething
}
else{
//printErrorMessages
}
[/code]
But now, I try to make a subclass of java.lang.Throwable to catch Runtime Exceptions (like to check if a reference in my session or one of HttpSession object's attribute is null). I do it like this
[code language="Java"]
try{
//doSomething
if (someValue==null){
throw new ACustomException();
}
}
catch(ACustomException acex){
//printErrorMessage
}
[/code]
I personally find it neater than the previous method. How about you?