Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Chained Exceptions in C#
Chained Exceptions are a chain of try-catch statements that handle exceptions. To create a chain of exceptions i.e. chained exceptions −
Set the first try-catch −
Example
static void Main(string[] args) {
try {
One();
} catch (Exception e) {
Console.WriteLine(e);
}
}
Now try-catch under method One() −
Example
static void One() {
try {
Two();
} catch (Exception e) {
throw new Exception("First exception!", e);
}
}
The method Two() also continues chained exception.
Example
static void Two() {
try {
Three();
} catch (Exception e) {
throw new Exception("Second Exception!", e);
}
}
Now 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!");
}
On running the above, the exceptions would be handled like this −
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
Advertisements
