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
.
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 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.
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.
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.
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 }
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