try{...} catch {...} finally{...} 各种情况代码的执行情况

本文通过两个测试案例详细介绍了C#中try-catch-finally结构的行为。当try块内发生异常时,会跳过后续代码并进入catch块处理异常;若未发生异常,则直接跳过catch块。无论是否发生异常,finally块及其后的代码均会被执行。
 1            try
 2             {
 3                 int i = Convert.ToInt32(Console.ReadLine());
 4                 Console.WriteLine("in the 'try'");
 5             }
 6             catch
 7             {
 8                 Console.WriteLine("in the 'catch'");
 9             }
10             finally
11             {
12                 Console.WriteLine("in the 'finally'");
13             }
14             Console.WriteLine("After the 'finally'");
15             Console.ReadKey();

对2种情况进行测试

1:try中的语句执行中有异常

2:try中的语句执行中没有异常

第1种情况:

输入999999999999999999

执行结果为

999999999999999999
in the 'catch'
in the 'finally'
After the 'finally'

分别执行了catch 、finally、finally后的代码

 

第2种情况:

输入123

执行结果为

123
in the 'try'
in the 'finally'
After the 'finally'

分别执行了try、finally、finally后的代码

 

结论:1.try中的代码执行有异常时,其(try中有异常的代码)后面的代码不执行,执行catch中的代码

   2.try中的代码执行没有异常时,catch中的代码不执行

     3.finally中的代码和try...catch..finally后的代码总是要执行

 

  

 

转载于:https://www.cnblogs.com/ronk/p/3163918.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值