孤独的猫

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

C#中可以用try..catch..Finally进行异常处理,try后面跟要执行的语句,catch为如有异常,对异常进行处理,Finally做清理工作,这部分必须执行,如下示例:

1 /*
2 Example13_1.cs illustrates a try, catch, and finally block
3  */
4
5 using System;
6
7 class Example13_1
8 {
9
10 public static void Main()
11 {
12
13 try
14 {
15
16 // code that throws an exception
17 int zero = 0;
18 Console.WriteLine("In try block: attempting division by zero");
19 int myInt = 1 / zero; // throws the exception
20 Console.WriteLine("You never see this message!");
21
22 }
23 catch
24 {
25
26 // code that handles the exception
27 Console.WriteLine("In catch block: an exception was thrown");
28
29 }
30 finally
31 {
32
33 // code that does any cleaning up
34 Console.WriteLine("In finally block: do any cleaning up here");
35
36 }
37
38 }
39
40 }
posted on 2011-05-08 15:23  孤独的猫  阅读(1057)  评论(0编辑  收藏  举报