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?

Published 01-22-2008 8:46 PM by lamia
Filed under: ,

Comments

Thursday, January 24, 2008 1:37 AM by cruizer

# re: If-Else vs Throwing an Exception to handle errors

it depends.

exceptions are more expensive in terms of resources. for me i'd rather use exceptions for EXCEPTIONAL situations, like network failures or timeouts. for stuff that can be avoided by an if condition, I'd rather use that. a common example that's given is the divide by zero error in a calculator program. would you rather let it throw the divide by zero exception, or would you rather catch if something is being divided by zero even before the division is performed?

Thursday, January 24, 2008 7:25 PM by lamia

# re: If-Else vs Throwing an Exception to handle errors

Yeah, I agree. Well perhaps the situation I'm trying to avoid is making your code look like this

if(){

 if(){

 }

 else{

   if(){

   }

   else{

   }

 }

}

else{

 if(){

 }

 else{

   if(){

   }

   else{

   }

 }

}

which then only confuses the reader(could be yourself). But then again you're right. It could highly depend on the situation.

Thanks!

Friday, January 25, 2008 1:03 AM by cruizer

# re: If-Else vs Throwing an Exception to handle errors

nakakatakot naman yang if na yan. well, using exceptions to break out of such funkiness is one way, but i believe there's a better way to refactor that code without needing to use exceptions.

basta sa akin personally, i just use exceptions for exceptional circumstances, yun bang "hindi mo pwede maiwasan."