Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

executing a method in case both the try catch fail

Tags:

c#

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?

like image 740
frenchie Avatar asked Sep 22 '14 21:09

frenchie


2 Answers

Perhaps nested try/catch can be used:

try
{
    TheString = SomeDangerousMethod();
}
catch
{
  try
  {
      TheString = SomeSaferMethod();
  }
  catch
  {
      TheString = SuperSaferMethod();
  }
}

return TheString;
like image 193
AlexD Avatar answered Oct 10 '22 03:10

AlexD


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();
like image 24
Vlad Avatar answered Oct 10 '22 01:10

Vlad