Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good to use try catch within a try catch? [duplicate]

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
    }
}
like image 722
HotTester Avatar asked Dec 07 '12 08:12

HotTester


People also ask

Can I use try catch inside try catch?

Yes, we can declare a try-catch block within another try-catch block, this is called nested try-catch block.

Can you have 2 try catch?

You cannot have multiple try blocks with a single catch block. Each try block must be followed by catch or finally.

Can we use try within try?

In Java, we can use a try block within a try block. Each time a try statement is entered, the context of that exception is pushed on to a stack. Given below is an example of a nested try. In this example, inner try block (or try-block2) is used to handle ArithmeticException, i.e., division by zero.

Can you use multiple catches with one try?

Yes, we can define one try block with multiple catch blocks in Java.


3 Answers

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.

like image 173
Itay Karo Avatar answered Sep 22 '22 02:09

Itay Karo


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;
    }
}
like image 44
jb. Avatar answered Sep 23 '22 02:09

jb.


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

like image 32
Chadwick13 Avatar answered Sep 21 '22 02:09

Chadwick13