Java - is it bad practice to do a try/catch inside a try/catch?

GeekedOut picture GeekedOut · May 20, 2012 · Viewed 44.8k times · Source

I have some code that I want to execute if an exception happens. But that code can also generate an exception. But I have never seen people do a try/catch inside another try/catch.

Is what I am doing poor practice and maybe there is a better way of doing this:

 Uri uri = Uri.parse("some url");
 Intent intent = new Intent(Intent.ACTION_VIEW, uri);

 try 
 {
     startActivity(intent);
 } 
 catch (ActivityNotFoundException anfe) 
 {
     // Make some alert to me

     // Now try to redirect them to the web version:
     Uri weburi = Uri.parse("some url");
     try
     {
         Intent webintent = new Intent(Intent.ACTION_VIEW, weburi);
         startActivity(webintent);
     }
     catch ( Exception e )
     {
         // Make some alert to me                        
     }
 }

It seems kind of awkward. Is there something that might be wrong with it?

Answer

T.J. Crowder picture T.J. Crowder · May 20, 2012

It's fine, although if your exception handling logic is that complex, you might consider breaking it out into its own function.