views:

25

answers:

3

what is the best way to handle an exception?
and why should i never write:

catch (Exception ex) { throw ex; }
A: 

Why would you catch the expection to just throw it again, if you were to catch the exception and do something other than just throw it, it would be fine!

try 
{
}
catch(Exception ex)
{
 // do something like log the exception
 throw ex; // let another catch block handle the expection.
}
madsleejensen
+1  A: 

The best way to handle an exception is to do something meaningful in the catch block (the one which in your example contains throw ex). The definition of "meaningful" completely depends on your needs.

You should not do catch (Exception ex) { throw ex; } because that brakes the exception chain. It is perfectly fine to catch an exception, handle it and re-throw so that the calling code can see it, but you should be doing so like this:

catch (Exception ex) { /* handling code; */ throw; } 
GSerg
This works fine in C++, but doesn't in, for example, Java. Which is why the original poster *really* needs to identify the language he's asking about.
JUST MY correct OPINION
@JUST In fact, I assumed C# by default ;) Considering the other OP's questions, it might even be a good assumption.
GSerg
A: 

If you're in a position in the code where you can deal with the exceptional case that is described by the exception then you should:

try 
{
    // code that might throw an exception
} 
catch 
{
    // deal with the exception here, for example ask the user to re-enter
    // the input that threw the exception
}

If you're not in a position to handle the exceptional case, there's no point catching the exception - just let it pass up the call stack until the calling code is in a position to handle it.

Jackson Pope