Verma Aman :
I read about nested try
-catch
statements and I can't help but wonder what is the actual point of using nested try
? The contents of the inner try
are already in the outer try
, and if an exception is to be caught, the outer try
-catch
will handle it. So why use inner try
?
For example:
Code 1:
try
{
Statement A;
Statement B;
try
{
Statement C;
Statement D;
}
catch(CException e) { ... }
catch(DException e) { ... }
}
catch(AException e) { ... }
catch(BException e) { ... }
Code 2:
try
{
Statement A;
Statement B;
Statement C;
Statement D;
}
catch(AException e) { ... }
catch(BException e) { ... }
catch(CException e) { ... }
catch(DException e) { ... }
Correct me if I'm wrong but don't these two code snippets above perform the same task?
pkpnd :
You can have a loop around the inner try, to catch exceptions multiple times without exiting the loop.
try {
for (int i = 0; i < 10; i++) {
try {
someOperationThatOftenFails();
} catch (SomeCommonException e) {
...
}
}
} catch (SomeRareFatalException e) {
...
}
In this scenario, nested try blocks are the only way of catching SomeCommonException
multiple times without exiting the loop, but also causing SomeRareFatalException
to exit the loop the first time it occurs.