Created
March 11, 2020 07:58
-
-
Save fatihbahceci/f6e70fa7916dacb5ff8de8addeb4c3c5 to your computer and use it in GitHub Desktop.
Multi try catch example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//C# Interactive code. Select all and press (Ctrl + E, Ctrl + E) | |
/// <summary> | |
/// Tries each action until success | |
/// </summary> | |
/// <param name="onException">Action on each exception</param> | |
/// <param name="acts">Actions which is will try</param> | |
/// <returns></returns> | |
int MultiTryCatchUntil(Action<Exception> onException, params Action[] acts) | |
{ | |
int i = 0; | |
while (i < acts.Length) | |
{ | |
try | |
{ | |
acts[i](); | |
return i; | |
} | |
catch (Exception e) | |
{ | |
i++; | |
try { onException(e); } catch { } | |
} | |
} | |
return -1; | |
} | |
void throwException() | |
{ | |
throw new Exception("I am completely failure monument"); | |
} | |
void test() | |
{ | |
int successActionIndex = MultiTryCatchUntil( | |
//Action for exceptions | |
(Exception e) => | |
{ | |
Console.WriteLine("Error: " + e.Message); | |
}, | |
//Action 0 | |
() => | |
{ | |
int i = 0; | |
var x = 10 / i; | |
}, | |
//Action 1 | |
() => | |
{ | |
object o = null; | |
var s = o.ToString(); | |
}, | |
//Action 2 | |
throwException, | |
//Action 3 | |
() => | |
{ | |
Console.WriteLine("Howdy friend! How are you!"); | |
}, | |
//Action 3 (This one will never executed) | |
() => | |
{ | |
Console.WriteLine("Why nobody likes me!"); | |
} | |
); | |
Console.WriteLine(successActionIndex >= 0 ? $"Action {successActionIndex} was succesful" : "All actions are failed"); | |
} | |
test(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment