Chinaunix首页 | 论坛 | 博客
  • 博客访问: 12399508
  • 博文数量: 1293
  • 博客积分: 13501
  • 博客等级: 上将
  • 技术积分: 17974
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-08 18:11
文章分类

全部博文(1293)

文章存档

2019年(1)

2018年(1)

2016年(118)

2015年(257)

2014年(128)

2013年(222)

2012年(229)

2011年(337)

分类: 嵌入式

2012-09-22 09:59:06

一、MSDN中对try-finally语句的解释


finally 块用于清除 try 块中分配的任何资源,以及运行任何即使在发生异常时也必须执行的代码。控制总是传递给 finally 块,与 try 块的退出方式无关。

备注

catch 用于处理语句块中出现的异常,而 finally 用于保证代码语句块的执行,与前面的 try 块的退出方式无关。

 

二、案例说明


在此例中,有一个导致异常的无效转换语句。当运行程序时,您收到一条运行时错误信息,但 finally 子句仍继续执行并显示输出。


1、案例代码


  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;

  5. namespace Finally_test
  6. {
  7.     class Program
  8.     {
  9.         static int i = 123;
  10.         static string s = "Some string";
  11.         static object o = s;

  12.         static void Main(string[] args)
  13.         {

  14.             Test_Exception_Function();
  15.             Console.WriteLine("in Main,After Excute Test_Exception_Function........!");
  16.             Console.ReadLine();

  17.         }

  18.         static void Test_Exception_Function()
  19.         {
  20.             try
  21.             {
  22.                 // Invalid conversion; o contains a string not an int
  23.                 i = (int)o;
  24.             }
  25.             catch (Exception InvalidException)
  26.             {
  27.                 Console.WriteLine("Find Exception in catch " + InvalidException.ToString());
  28.                 Console.ReadLine();
  29.                 return;
  30.             }
  31.             finally
  32.             {
  33.                 /* 如果上面的异常成立,finally里的语句先被执行,才执行return */
  34.                 Console.Write("in finally打印 : i = {0}", i);
  35.                 Console.ReadLine();
  36.             }
  37.             /* 如果上面的异常成立, 这个控制台语句,直接被跳过 */
  38.             Console.WriteLine(" End of Test_Exception_Function ");
  39.         }

  40.     }
  41. }

2、执行效果图

image


三、结论

使用了finally,即使catch中使用Return,还是先会执行完finaly中的语句才会跳出子过程。

上面Test_Exception_Function函数中,try catch finally语句块后的Console.WriteLine(" End of Test_Exception_Function "); 就被无辜的跳过了,直接不执行

阅读(2829) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~