To answer the question posted, which is if you can use try
on multiple things without nesting the try-catch
statements, no.
However, what you can do though is, aside from an if-else as posted in one of the answers, you can catch multiple things.
So perhaps you might want a combination of both controls:
Instead of having getJSONData throw exceptions, you could just have it return null, in which you will have a nice flow control of if-else statements, all inside a try-catch, and if something really bad/exceptional happens, throw the a specific exception, and the corresponding catch statement will handle it.
The reason why try-catches are not a good flow control: Exceptions are costly when thrown, because of the stack trace it has to hold even if not used, this is fine in quick and dirty programming, but not in situations where performance is key.That is why exceptions should only be thrown if they are truly exceptional. See this opinion based Q&A on true-false vs exceptions, where my elaboration on that issue is located as well.
Something like this would be good:
public string imgName()
{
try
{
JSONdata a = getJSONmethodA();
if(a == null)
a = getJSONmethodB();
if(a == null)
a = getJSONmehtodC();
return a;
}
catch(Exception unresolvableExceptionA)
{
//error handling
}
catch(Exception verybadExceptionB)
{
//special error handling for exception B
}
}
Here's a related SO question on this multiple catch structure.
You can also add a finally
in a try-catch
for code that will always execute regardless of whether your try was successful or not. This is useful in closing connections, or return true/false depending on your needs as a status code for other functions that use that method.