Chained exceptions in C#

WBOY
Release: 2023-09-01 22:09:06
forward
736 people have browsed it

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);
   }
}
Copy after login

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

Example

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

Method Two() will also continue to chain exceptions.

Example

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

Now comes the next method.

Example

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

The takes us to the last.

Example

static void Last() {
   throw new Exception("Last exception!");
}
Copy after login

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
Copy after login

The above is the detailed content of Chained exceptions in C#. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!