Home >Backend Development >C#.Net Tutorial >Chained exceptions in C#

Chained exceptions in C#

WBOY
WBOYforward
2023-09-01 22:09:06763browse

C# 中的链式异常

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 −

Example

static void Main(string[] args) {
   try {
      One();
   } catch (Exception e) {
      Console.WriteLine(e);
   }
}

Now try using try-catch under method One() −

Example

static void One() {
   try {
      Two();
   } catch (Exception e) {
      throw new Exception("First exception!", e);
   }
}

Method Two() will also continue to chain exceptions.

Example

static void Two() {
   try {
      Three();
   } catch (Exception e) {
      throw new Exception("Second Exception!", e);
   }
}

Now comes the next method.

Example

static void Three() {
   try {
      Last();
   } catch (Exception e) {
      throw new Exception("Third Exception!", e);
   }
}

The takes us to the last.

Example

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete
Previous article:Using datetime in C#Next article:Using datetime in C#