Java - is it bad practice to do a try/catch inside a try/catch?
Solution 1:
It's fine, although if your exception handling logic is that complex, you might consider breaking it out into its own function.
Solution 2:
It is a bad practice to write code with so many levels of nesting, especially in try-catch
- so I would say: avoid. On the other hand throwing an exception from catch
block is unforgivable sin, so you should be very careful.
My advice - extract your catch
logic into a method (so catch
block is simple) and make sure this method will never throw anything:
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");
Intent webintent = new Intent(Intent.ACTION_VIEW, weburi);
silentStartActivity(webintent)
}
//...
private void silentStartActivity(Intent intent) {
try
{
startActivity(webintent);
}
catch ( Exception e )
{
// Make some alert to me
}
}
Also it seems (I might be wrong) that you are using exceptions to control program flow. Consider standard return value if throwing ActivityNotFoundException
is not an exceptional situation but it might happen under normal circumstances.