Java – How is a nested Try/Catch (inside the try) not an anti-pattern

anti-patternsjava

I've seen a debate on this. Nested trys in the catch, I can see that being okay. The outer try has already triggered a catch by that time, hence no scope issues. The other way….hides errors (it is a scope issue).

try {

     try{
        Throws exception; 
        } catch (exception innerE) {
         outerE.printStackTrace(); /* I know the error , printing but have no way of passing what I know to the outer try*/
     }

} 

catch (exception outerE){
 outerE.printStackTrace(); /* Going to override the inner and not say anything because the inner catch is not visible to my scope */  
}

How is this not an anti-pattern?

Best Answer

There are proper uses of this pattern (as there are improper uses of it). As mentioned in the comments, additional information can be included by the inner catch:

try 
{
  try 
  {
    throw new GenericException("Generic message");
  }
  catch (Exception innerEx) 
    {
    // rollback some changes perhaps
    throw new MoreDetailedException(innerEx, "More details supplied here as well as by the type of exception");
  }
}
catch (Exception outerEx)
{
  Console.WriteLine(outerEx);
}

You can also use it to catch processing errors that you are able to recover from in your inner loop, and keep processing:

try 
{
  try 
  {
    _response = ProcessInputFromUser();
  }
  catch (Exception innerEx) 
  {
    _response = 0;
  }

  ProcessResponse(_response);
}
catch (Exception outerEx)
{
  Console.WriteLine(outerEx);
}

The improper way of handling this is to log the error twice, catch and simply rethrow, etc:

try 
{
  try 
  {
  }
  catch (Exception innerEx) 
  {
    Console.WriteLine(innerEx);
    throw;
  }
}
catch (Exception outerEx)
{
  Console.WriteLine(outerEx);
}
Related Topic