I have a method doSomething()
that has one try catch block, within which I call another method.
public void doSomething()
{
try
{
doSomethingElse();
}
catch
{
// catch implementation goes here
}
}
In that other method doSomethingElse()
I don't have any try catch block. I am depending on the main method's try-catch to handle the exception. If there are any exceptions in doSomethingElse()
they will be bubbled up to the method doSomething's try-catch block.
Is there anything wrong with this approach?
Thanks for your time.
This is perfectly legitimate.
Let exceptions bubble up to where you can/know what to do with them.
It is good practice not to litter your code with try/catch blocks that don't add anything.
However, having empty catch blocks is bad practice (though I am assuming the code you have posted is a simplified version omitting the catch block code).
Nothing wrong with that.
As others have said, don't swallow exceptions. It may also be a good idea not to throw a new exception; rather, just catch (Exception)
and throw
it. Of course, it should also be noted to try and be specific with exceptions, and not just use the default Exception
.
It's smelly. Catching an exception requires that you restore the program state, as though doSomethingElse() was never called. It very much depends on what the method does but it is generally pretty unusual to write a method without any side effects whatsoever. If it has any then those side effects need to be canceled. Only doSomethingElse() can do so, the doSomething() method is powerless to guess how many of those side effects were actually executed. And can thus not reliably restore state.
This is especially the case when you catch all exceptions. You'll grab the nasty ones as well. Like AccessViolation or FatalExecutionEngineError, exceptions that leave the CLR itself in a unknown state, you can never restore that. What happens next is quite unpredictable. You'll get a flurry of additional exceptions only if you're lucky. Diagnosing them is impossible, you threw away valuable info.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With