Is it good practice to have more than one try{} catch{}
statement per method?
In my point of view it is good practice to have each method handle only a single task. As such you'll rarely need to have multiple try/catch blocks within a single method. However, I don't see any problems with it.
As Lisa pointed out you should catch specific exceptions and only catch the exceptions the method can actually handle.
If you know the type of Exceptions that could occur beforehand, you can have a single try and catch each of those exceptions, should you want to handle them differently. For example:
try
{
// a bunch of risky code
}
catch (SpecificException1 ex1)
{
// handle Specific Exception 1
}
catch (SpecificException2 ex2)
{
// handle Specific Exception 2
}
catch (SpecificException3 ex3)
{
// handle Specific Exception 3
}
catch (Exception ex)
{
// handle an exception that isn't specific
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With