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
}
}
Yes, we can declare a try-catch block within another try-catch block, this is called nested try-catch block.
You cannot have multiple try blocks with a single catch block. Each try block must be followed by catch or finally.
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.
Yes, we can define one try block with multiple catch blocks in Java.
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.
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;
}
}
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
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