Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Try and Catch blocks [closed]

I have nested try-catch blocks in a custom C# code for SharePoint. I want to execute the code in only one catch block (the inner one) when the code inside the inner try block throws an exception.

try {  //do something     try    {         //do something              if exception is thrown, don't go to parent catch     }    catch(Exception ex) {...}  } catch(Exception ex) { .... } 

I know I can use different types of exceptions but that's not what I am looking for.

Summary

If exception occurs, I don't want it to reach the parent catch in addition to the inner catch.

like image 545
Mathematics Avatar asked Sep 13 '13 09:09

Mathematics


People also ask

Is it bad to have nested try catch?

Nesting try-catch blocks severely impacts the readability of source code because it makes it to difficult to understand which block will catch which exception.

How do you resolve a nested try catch?

How to Avoid the Nesting? Extracting the nested part as a new method will always work for any arbitrarily nested Try-Catch-Finally block. So this is one trick that you can always use to improve the code.

What is true about nested try catch block?

When a try catch block is present in another try block then it is called the nested try catch block. Each time a try block does not have a catch handler for a particular exception, then the catch blocks of parent try block are inspected for that exception, if match is found that that catch block executes.

How would you handle multiple catch blocks for a nested try block explain with example?

Nested try block is a block in which we can implement one try catch block into another try catch block. The requirement of nested try-catch block arises when an exception occurs in the inner try-catch block is not handled by the inner catch blocks then the outer try-catch blocks are checked for that exception.


1 Answers

If you don't want to execute the outer exception in that case you should not throw the exception from the inner catch block.

try {  //do something    try    {       //do something              IF EXCEPTION HAPPENs don't Go to parent catch    }    catch(Exception ex)    {        // logging and don't use "throw" here.    } } catch(Exception ex) {    // outer logging } 
like image 94
Sachin Avatar answered Oct 19 '22 10:10

Sachin