I have some code that looks like this:
string TheString = string.Empty;
try
{
TheString = SomeDangerousMethod();
}
catch
{
TheString = SomeSaferMethod();
}
return TheString;
It turns out that SomeSaferMethod
is not so safe and can also fail in some edge case. For this reason, I created a method called SuperSafeMethod
that I want to call in case the SomeSaferMethod
also fails in the catch statement.
How can I change my try catch so that there's a third level of execution that triggers if both SomeDangerousMethod
and SomeSaferMethod
fail?
Perhaps nested try/catch
can be used:
try
{
TheString = SomeDangerousMethod();
}
catch
{
try
{
TheString = SomeSaferMethod();
}
catch
{
TheString = SuperSaferMethod();
}
}
return TheString;
You could do the following to avoid nesting. This allows you to use as many methods as you want, in a cleaner fashion.
Func<string>[] methods = { SomeDangerousMethod, SomeSaferMethod, SuperSafeMethod };
foreach(var method in methods)
{
try
{
TheString = method();
break;
}
catch { }
}
if (string.IsNullOrEmpty(TheString))
throw new TooMuchUnsafetyException();
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