c#基础-异常处理
跟java大同小异,示例代码如下:
1 /*using System;
2
3 class Sample
4 {
5 public static void Main(string[] args)
6 {
7 long factorial = 1;
8 long num = Int64.Parse(args[0]);
9 try
10 {
11 checked
12 {
13 //计算num的阶乘
14 for(long cur = 1;cur <=num;cur++)
15 factorial *= cur;
16 }
17 }
18 catch(OverflowException oe)
19 {
20 Console.WriteLine("计算{0}的阶乘时发生异常",num);
21 Console.WriteLine("{0}",oe.Message);
22 return;
23 }
24 Console.WriteLine("{0}的阶乘是{1}",num,factorial);
25
26 }
27 }
28 */
29 using System;
30 class Sample
31 {
32 static void f(string s)
33 {
34 if(s == null)
35 throw(new ArgumentNullException());
36 }
37 public static void Main()
38 {
39 try
40 {
41 string s = null;
42 f(s);
43 }
44 catch(ArgumentNullException e)
45 {
46 Console.WriteLine("Exception:{0}",e.Message);
47 }
48 finally
49 {
50 Console.WriteLine("excute finally centence");
51 }
52 }
53 }
2
3 class Sample
4 {
5 public static void Main(string[] args)
6 {
7 long factorial = 1;
8 long num = Int64.Parse(args[0]);
9 try
10 {
11 checked
12 {
13 //计算num的阶乘
14 for(long cur = 1;cur <=num;cur++)
15 factorial *= cur;
16 }
17 }
18 catch(OverflowException oe)
19 {
20 Console.WriteLine("计算{0}的阶乘时发生异常",num);
21 Console.WriteLine("{0}",oe.Message);
22 return;
23 }
24 Console.WriteLine("{0}的阶乘是{1}",num,factorial);
25
26 }
27 }
28 */
29 using System;
30 class Sample
31 {
32 static void f(string s)
33 {
34 if(s == null)
35 throw(new ArgumentNullException());
36 }
37 public static void Main()
38 {
39 try
40 {
41 string s = null;
42 f(s);
43 }
44 catch(ArgumentNullException e)
45 {
46 Console.WriteLine("Exception:{0}",e.Message);
47 }
48 finally
49 {
50 Console.WriteLine("excute finally centence");
51 }
52 }
53 }