Reputation: 63
When throwing exceptions between multiple methods, should all methods re-throw the exception? for example
Method1()
{
Method2();
}
Method2()
{
try
{
// Do something
}
catch
{
throw;
}
}
try
{
Method1();
}
catch
{
// Do something about exception that was thrown from Method2()
}
Notice how in Method1()
, I didn't need to wrap Method2()
in a try
block, should I be?
Upvotes: 6
Views: 1504
Reputation: 262919
You don't need to wrap everything in try
blocks.
You should only try
when you want to catch
something, and you should only catch
something in the following cases:
throw
),Upvotes: 9
Reputation: 244722
You do not need to try, catch, and rethrow exceptions unless you have some particular reason for catching them in the first place. Otherwise, they'll automatically get bubbled up from the lower level functions that throw them to the highest level function in your code. Essentially, you can think of them as getting "rethrown" all the way up, even though this isn't technically what is happening.
In fact, most of the time that you see a try
/catch
block written, it's incorrect. You should not catch exceptions unless you can actually handle them. It's utterly pointless (and in fact considered to be bad practice) to catch exceptions just to rethrow them. Do not wrap all of your code within try
blocks.
Note that by "handle them", I mean that your code in the catch
block will take some specific action based on the particular exception that was thrown that attempts to correct the exceptional condition.
For example, for a FileNotFoundException
, you might inform the user that the file could not be found and ask them to choose another one.
See my answer here for more detail and a thorough discussion of "exception handling best practices".
Upvotes: 8