嵌套的try/catch块和创建异常对象

可以嵌套使用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 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值