Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception handling try catch inside catch

I recently came across code written by a fellow programmer in which he had a try-catch statement inside a catch!

Please forgive my inability to paste the actual code, but what he did was something similar to this:

try {  //ABC Operation } catch (ArgumentException ae) {    try    {       //XYZ Operation    }    catch (IndexOutOfRangeException ioe)    {       //Something    } } 

I personally feel that it is some of the poorest code I have ever seen! On a scale of 1 to 10, how soon do you think I should go and give him a piece of my mind, or am I over-reacting?

EDIT: What he is actually doing in the catch, he is performing some operations which can/should be done when the initial try fails. My problem is with having a clean code and maintainability. Delegating the exception from the first catch to a different function or the calling function would be OK, but adding more code which may or may not throw an exception into the first catch, is what I felt was not good. I try to avoid multiple stacked "if-loop" statements, I found this equally bad.

like image 956
topgun_ivard Avatar asked Aug 19 '10 20:08

topgun_ivard


People also ask

Can you have try-catch inside try-catch in Java?

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.

Can we use try and catch for exception handling?

Place any code statements that might raise or throw an exception in a try block, and place statements used to handle the exception or exceptions in one or more catch blocks below the try block. Each catch block includes the exception type and can contain additional statements needed to handle that exception type.

Is nested try-catch OK?

I actually don't think there's anything inherently wrong about nested Try / Catch blocks, except that they can be difficult to navigate and are likely a sign that you could do some refactoring (the inner Try / Catch into its own method, for example).

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.


1 Answers

Why is that bad? It's no different conceptually than:

void TrySomething() {    try {      } catch (ArgumentException) {         HandleTrySomethingFailure();    } }  void HandleTrySomethingFailure() {     try {      } catch (IndexOutOfRangeException) {      } } 

Before you go over there and give him a piece of your brain (try the parietal lobe, it's particularly offensive) , what exactly are you going to say to him? How will you answer the proverbial "why?"

What's even more ironic is that when the jitter inlines this code, it will look exactly like your example.

-Oisin

like image 53
x0n Avatar answered Sep 20 '22 03:09

x0n