Is it good to use try catch within a try catch?

46,224

Solution 1

No particular problem with this especially if you want to handle the exceptions differently.
However, if the inner exception and the outer exception are of different types E1, E2 respectively and E1 is not a parent of E2, you can have two adjacent catch clauses.

try
{
  // do something
}
catch (E1 e1)
{
}
catch (E2 e2)
{
}

As noted by Rob and J.Steen - this is slightly different than the case in the question as in this case is E1 is thrown the code after it will not be executed.

Solution 2

A nested try/catch is fine. what you want to stay away from is changing the logical flow of your code based on the try catch. In other words, you shouldn't treat a try/catch as an if/else block. so this isn't ideal:

//over the top example just to demonstrate my point

public bool IsNumberTen(int x)
{
    try
    {
        if(x > 10)
            throw new NumberTooHighException();
        else if(x < 10)
            throw new NumberTooLowException();
        else
            return true;

    }
    catch(NumberTooHighException)
    {
        return false;
    }
    catch(NumberTooLowException)
    {
        return false;
    }
}

Solution 3

This item suggests that its not a bad thing and that you would only have to handle the error in another way any way.

Exception handling try catch inside catch

Solution 4

I don't see why not. If you have logic in the catch which may fail or raise an exception that requires handling then it makes sense.

Share:
46,224
HotTester
Author by

HotTester

coding and testing....

Updated on July 28, 2022

Comments

  • HotTester
    HotTester almost 2 years

    Possible Duplicate:
    Are nested Try/Catch blocks a bad idea?

    Currently I am using try catch within try catch ? The current senario requires it in our application.

    void MyFun()
    {
        try
        {
            //Process logic 1
            // ......
            try
            {
                //Process logic 2
                // ......
            } catch (Exception ex)
            {
                //write an error details in database
            }
    
            //Process Logic 3
            // ......
    
        } catch (Exception ex)
        {
            //show error msg
        }
    }