關於C#異常處理!
來源:互聯網
上載者:User
1 using System;
2
3 namespace ConsoleApplication2
4 {
5 /// <summary>
6 /// Class1 的摘要說明。
7 /// </summary>
8 class Class1
9 {
10 static string[] eTypes={"none","simple","index","nested index"};
11 [STAThread]
12 static void Main(string[] args)
13 {
14 foreach(string eType in eTypes)
15 {
16 try
17 {
18 Console.WriteLine("Main() try block reached.");
19 Console.WriteLine("ThrowException(\"{0}\") called.",eType);
20 ThrowException(eType);
21 Console.WriteLine("Main() try block continues.");
22 }
23 catch(System.IndexOutOfRangeException e)
24 {
25 Console.WriteLine("Main() System.IndexOutOfRangeException catch "+
26 " block reched.Message:\n\"{0}\"",e.Message);
27 }
28 catch
29 {
30 Console.WriteLine("Main() general catch block reached.");
31 }
32 finally
33 {
34 Console.WriteLine("Main() finally block reached.");
35 }
36 Console.WriteLine();
37 }
38 }
39 static void ThrowException(string exceptionType)
40 {
41 Console.Write("ThrowException(\"{0}\")reached.",exceptionType);
42 switch(exceptionType)
43 {
44 case "none":
45 Console.WriteLine("Not throwing an exception.");
46 break;
47 case "simple":
48 Console.WriteLine("Throwing System.Exception.");
49 throw(new System.Exception());
50 break;
51 case "index":
52 Console.WriteLine("Throwing System.IndexOutOfRangeexception.");
53 eTypes[4]="error";
54 break;
55 case "nested index":
56 try
57 {
58 Console.WriteLine("ThrowException(\"nested index\"):"+"tyr block reached.");
59 Console.WriteLine("ThrowException(\"index\")called.");
60 ThrowException("index");
61 }
62 catch
63 {
64 Console.WriteLine("ThrowException(\"nested index\")general"+" catch block reached.");
65 }
66 finally
67 {
68 Console.WriteLine("ThrowException(\"nested index\")finally"+"block reached.");
69 }
70 break;
71 }
72 }
73 }
74 }
75
76 此異常的處理說明,異常產生後,如果在當前未做Try處理,則會返到上一級,如果還未做,則返回上一級的上一級.以此類推.如果被任意一級Catch到,則上一級不會再得到.