孤独的猫

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

可以自定义异常块如,catch (System.Exception myException),然后对myException进行访问,例如:

1 /*
2 Example13_2.cs illustrates the use of a
3 System.Exception object
4  */
5
6  using System;
7
8  class Example13_2
9 {
10
11 public static void Main()
12 {
13
14 try
15 {
16
17 int zero = 0;
18 Console.WriteLine("In try block: attempting division by zero");
19 int myInt = 1 / zero; // throws the exception
20
21 }
22 catch (System.Exception myException)
23 {
24
25 // display the exception object's properties
26 Console.WriteLine("HelpLink = " + myException.HelpLink);
27 Console.WriteLine("Message = " + myException.Message);
28 Console.WriteLine("Source = " + myException.Source);
29 Console.WriteLine("StackTrace = " + myException.StackTrace);
30 Console.WriteLine("TargetSite = " + myException.TargetSite);
31
32 }
33
34 }
35
36 }
1 /*
2 Example13_4.cs illustrates multiple catch blocks
3 */
4
5 using System;
6
7 class Example13_4
8 {
9
10 public static void Main()
11 {
12
13 try
14 {
15
16 int[] myArray = new int[2];
17 Console.WriteLine("Attempting to access an invalid array element");
18 myArray[2] = 1;
19
20 }
21 catch (DivideByZeroException e)
22 {
23
24 // code that handles a DivideByZeroException
25 Console.WriteLine("Handling a System.DivideByZeroException object");
26 Console.WriteLine("Message = " + e.Message);
27 Console.WriteLine("StackTrace = " + e.StackTrace);
28
29 }
30 catch (IndexOutOfRangeException e)
31 {
32
33 // code that handles an IndexOutOfRangeException
34 Console.WriteLine("Handling a System.IndexOutOfRangeException object");
35 Console.WriteLine("Message = " + e.Message);
36 Console.WriteLine("StackTrace = " + e.StackTrace);
37
38 }
39 catch (Exception e)
40 {
41
42 // code that handles a generic Exception: all other exceptions
43 Console.WriteLine("Handling a System.Exception object");
44 Console.WriteLine("Message = " + e.Message);
45 Console.WriteLine("StackTrace = " + e.StackTrace);
46
47 }
48
49 }
50
51 }

也可定义多个catch块,对多个异常情况进行处理,如:

posted on 2011-05-08 15:27  孤独的猫  阅读(4386)  评论(0编辑  收藏  举报