Linked exceptions are a series of try-catch statements that handle exceptions. To create a chain of exceptions i.e. chain exceptions −
Set the first try-catch −
static void Main(string[] args) { try { One(); } catch (Exception e) { Console.WriteLine(e); } }
Now try using try-catch under method One() −
static void One() { try { Two(); } catch (Exception e) { throw new Exception("First exception!", e); } }
Method Two() will also continue to chain exceptions.
static void Two() { try { Three(); } catch (Exception e) { throw new Exception("Second Exception!", e); } }
Now comes the next method.
static void Three() { try { Last(); } catch (Exception e) { throw new Exception("Third Exception!", e); } }
The takes us to the last.
static void Last() { throw new Exception("Last exception!"); }
When running the above code, the exception will be handled as follows −
System.Exception: First exception! ---< System.Exception: Middle Exception! ---< System.Exception: Last exception! at Demo.Two () [0x00000] in <199744cb72714131b4f5995ddd1a021f>:0 --- End of inner exception stack trace --- at Demo.Two () [0x00016] in <199744cb72714131b4f5995ddd1a021f>:0 at Demo.One () [0x00000] in <199744cb72714131b4f5995ddd1a021f>:0 --- End of inner exception stack trace --- at Demo.One () [0x00016] in <199744cb72714131b4f5995ddd1a021f>:0 at Demo.Main (System.String[] args) [0x00000] in <199744cb72714131b4f5995ddd1a021f>:0
The above is the detailed content of Chained exceptions in C#. For more information, please follow other related articles on the PHP Chinese website!