可以嵌套使用try..catch块,如下:

1 /*
2 Example13_5.cs illustrates a nested try/catch block;
3 the nested if throws an exception that is propagated to the
4 outer exception
5  */
6
7  using System;
8
9 class Example13_5
10 {
11
12 public static void Main()
13 {
14
15 try
16 {
17
18 // a nested try and catch block
19 try
20 {
21
22 int[] myArray = new int[2];
23 Console.WriteLine("Attempting to access an invalid array element");
24 myArray[2] = 1; // throws the exception
25
26 }
27 catch (DivideByZeroException e)
28 {
29
30 // code that handles a DivideByZeroException
31 Console.WriteLine("Handling a DivideByZeroException");
32 Console.WriteLine("Message = " + e.Message);
33 Console.WriteLine("StackTrace = " + e.StackTrace);
34
35 }
36
37 }
38 catch (IndexOutOfRangeException e)
39 {
40
41 // code that handles an IndexOutOfRangeException
42 Console.WriteLine("Handling an IndexOutOfRangeException");
43 Console.WriteLine("Message = " + e.Message);
44 Console.WriteLine("StackTrace = " + e.StackTrace);
45
46 }
47
48 }
49
50 }

可以显示创建一个异常对象,如Exception myException = new Exception("myException");

然后对myException进行处理,代码如下:

1 /*
2 Example13_8.cs illustrates creating and
3 throwing an exception object
4 */
5
6 using System;
7
8 class Example13_8
9 {
10
11 public static void Main()
12 {
13
14 try
15 {
16
17 // create a new Exception object, passing a string
18 // for the Message property to the constructor
19 Exception myException = new Exception("myException");
20
21 // set the HelpLink and Source properties
22 myException.HelpLink = "See the Readme.txt file";
23 myException.Source = "My Example13_8 Program";
24
25 // throw the Exception object
26 throw myException;
27
28 }
29 catch (Exception e)
30 {
31
32 // display the exception object's properties
33 Console.WriteLine("HelpLink = " + e.HelpLink);
34 Console.WriteLine("Message = " + e.Message);
35 Console.WriteLine("Source = " + e.Source);
36 Console.WriteLine("StackTrace = " + e.StackTrace);
37 Console.WriteLine("TargetSite = " + e.TargetSite);
38
39 }
40
41 }
42
43 }