Method execution if catch attempt fails

I have a code that looks like this:

string TheString = string.Empty; try { TheString = SomeDangerousMethod(); } catch { TheString = SomeSaferMethod(); } return TheString; 

It turns out that SomeSaferMethod not so secure and may also fail in some edge case. For this reason, I created a method called SuperSafeMethod that I want to call if SomeSaferMethod also does not work in the catch statement.

How can I change my try catch so that there is a third level of execution that fires if both SomeDangerousMethod and SomeSaferMethod fail?

Thanks.

+5
source share
2 answers

Perhaps you can use the nested try/catch :

 try { TheString = SomeDangerousMethod(); } catch { try { TheString = SomeSaferMethod(); } catch { TheString = SuperSaferMethod(); } } return TheString; 
+12
source

You can do the following to avoid nesting. This allows you to use as many methods as possible in a cleaner way.

 Func<string>[] methods = { SomeDangerousMethod, SomeSaferMethod, SuperSafeMethod }; foreach(var method in methods) { try { TheString = method(); break; } catch { } } if (string.IsNullOrEmpty(TheString)) throw new TooMuchUnsafetyException(); 
+6
source

Source: https://habr.com/ru/post/1203175/


All Articles