Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

one main try catch in method calling methods that don't implement a try-catch

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.

like image 210
user20358 Avatar asked Oct 12 '10 12:10

user20358


3 Answers

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).

like image 170
Oded Avatar answered Oct 17 '22 01:10

Oded


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.

like image 41
Harry Avatar answered Oct 17 '22 03:10

Harry


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.

like image 2
Hans Passant Avatar answered Oct 17 '22 02:10

Hans Passant