Learn how to use exception filtering technique introduced in C# 6.0.
This video has been published on YouTube.
Code Samples
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
namespace ExceptionFilters { class Program { static int Main(string[] args) { #region Old way of filtering exceptions int recoveryMode; try { DoOperation(null); //DoOperation(1,2,3,4); } catch (ArgumentOutOfRangeException ae) { LogException(ae); if (CanRecover(ae)) { Recover(ae); } else if (CanRecover(ae, out recoveryMode)) { Recover(ae, recoveryMode); } else if (ae.Message.Contains("warning")) { Recover(ae); } else { throw; } } catch (Exception e) { LogException(e); if (CanRecover(e)) { Recover(e); } else if (CanRecover(e, out recoveryMode)) { Recover(e, recoveryMode); } else if (e.Message.Contains("warning")) { Recover(e); } else { throw; } } #endregion Old way of filtering exceptions #region Exception Filters //return 0; try { DoOperation(null); //DoOperation(1,2,3,4); } catch (Exception e) when (LogException(e)) { //This block is intentianally left empty, just an exception is logged //in an exception filter } catch (Exception e) when (CanRecover(e)) { Recover(e); } catch (Exception e) when (CanRecover(e, out recoveryMode)) { Recover(e, recoveryMode); } catch( Exception e) when (e.Message.Contains("warning")) { Recover(e); } catch(ArgumentNullException ane) { //Handle argument null exception } #endregion Exception Filters return 0; //Success } #region Helper Methods private static void Recover(Exception e, int recoveryMode) { Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine($"Recovered {e.Message} Recovery mode: {recoveryMode}"); Console.ResetColor(); } static void Recover(Exception e) { Recover(e, 2); } static void DoOperation(params object[] arguments) { if (arguments == null) { throw new ArgumentException($"{nameof(arguments)} cannot be null."); } if (arguments.Length > 3) { throw new ArgumentOutOfRangeException(nameof(arguments), $"{nameof(arguments)} is out of range. Upto 3 arguments are allowed."); } } static bool CanRecover(Exception ex) { ArgumentOutOfRangeException aoore = ex as ArgumentOutOfRangeException; return aoore != null; } static bool CanRecover(Exception ex, out int recoveryMode) { recoveryMode = 1; return false; } static bool LogException(Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"Exception occured: {ex}"); Console.ResetColor(); return false; } #endregion Helper Methods } } |