C#--异常对象和多catch块

可以自定义异常块如,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块,对多个异常情况进行处理,如:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值