C# Exception異常 學習


@1:try - catch

Exception類幾個常用屬性的示例:   TargetSite,  StackTrace,  Source

示例1
 1 namespace _20130405
 2 {
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             Loop:
 8             try
 9             {                
10                 Console.WriteLine("Input Intager One:");
11                 int x = Convert.ToInt32(Console.ReadLine());
12                 Console.WriteLine("Input Intager Two:");
13                 int y = Convert.ToInt32(Console.ReadLine());
14                 Console.WriteLine("x / y = {0}", x / y);
15             }
16             catch (FormatException format)
17             {
18                 //Console.WriteLine(format.Message);
19                 Console.WriteLine(format.TargetSite);       //捕獲引發當前異常的方法
20                 Console.WriteLine();
21                 Console.WriteLine();
22                 Console.WriteLine(format.StackTrace);       //捕獲當前異常發生所經歷的方法的名稱和簽名
23                 Console.WriteLine();
24                 Console.WriteLine();
25                 Console.WriteLine(format.Source);           //捕獲或設置導致錯誤的應用程序或對象的名稱
26                 Console.WriteLine();
27                 Console.WriteLine();
28                 /*
29                 Input Intager One:
30                 1.0
31                 Void StringToNumber(System.String, System.Globalization.NumberStyles, NumberBuff
32                 er ByRef, System.Globalization.NumberFormatInfo, Boolean)
33 
34 
35                    在 System.Number.StringToNumber(String str, NumberStyles options, NumberBuffe
36                 r& number, NumberFormatInfo info, Boolean parseDecimal)
37                    在 System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo in
38                 fo)
39                    在 System.Convert.ToInt32(String value)
40                    在 _20130405.Program.Main(String[] args) 位置 F:\2013\20130405\20130405\Progr
41                 am.cs:行號 17
42 
43 
44                 mscorlib
45                  */
46             }
47             catch (DivideByZeroException zero)
48             {
49                 //Console.WriteLine(zero.Message);
50                 Console.WriteLine(zero.TargetSite);
51                 Console.WriteLine();
52                 Console.WriteLine();
53                 Console.WriteLine(zero.StackTrace);
54                 Console.WriteLine();
55                 Console.WriteLine();
56                 Console.WriteLine(zero.Source);
57                 Console.WriteLine();
58                 Console.WriteLine();
59                 /*                                 
60                 Input Intager One:
61                 1
62                 Input Intager Two:
63                 0
64                 Void Main(System.String[])
65 
66 
67                    在 _20130405.Program.Main(String[] args)
68 
69 
70                 20130405
71                  */
72             }           
73             catch (Exception e)
74             {
75                 //當捕獲多個異常時,若兩個catch塊的異常類存在繼承關系,則要先捕獲派生類的異常,再捕獲基類的異常.
76                 //否則,捕獲派生類異常的catch塊將不起作用,並且會在編譯時報錯. 所以此處的這個catch必須放在三個
77                 //catch中的最后
78                 Console.WriteLine(e.Message);
79             }
80             
81             goto Loop;
82         }
83     }
84 }

@2:try - finally

  在執行時,若沒有發生異常,try - finally語句將按正常方式執行,若try塊內存在異常,則將在執行完finally塊后,拋出異常.

  finally塊用於清除try塊中分配的任何資源,以及執行  即使發生異常也必須執行的  代碼.

@3:try - catch - finally

  在異常處理中最多只能有一個finally塊!

示例2
 1 static void Main(string[] args)
 2         {
 3             int sum = 0;
 4             try
 5             {
 6                 int[] a = {1, 3, 4, 5, 6};
 7                 for (int i = 0; i < 6; ++i)
 8                 {
 9                     sum += a[i];
10                 }
11                 Console.WriteLine("try中的:sum = {0}", sum);    //這條語句沒有執行
12                 //如果try塊中出現了異常,則程序終止try塊的語句,進入catch塊, 所以此處沒有進行輸出.
13             }
14             catch (ArgumentOutOfRangeException argu)
15             {
16                 Console.WriteLine(argu.Message);
17             }
18             catch (Exception e)
19             {
20                 Console.WriteLine(e.Message);
21             }
22             finally
23             {
24                 Console.WriteLine("finally中的:sum = {0}", sum);
25             }
26             Console.ReadLine();
27             /*運行結果:
28             索引超出了數組界限。
29             finally中的:sum = 19
30              */
31         }

@4:throw語句用於發出  在程序執行期間出現異常情況  的 信號.

  throw  表達式;

  其中表達式必須表示一個Exception類或它的派生類型,也可以在throw語句后沒有表達式,表示將異常再次拋出.

示例3
 1 static void Main(string[] args)
 2         {
 3             int i = 0;
 4             int count = 3;
 5             Console.WriteLine("Please Input the KeyWord:");
 6 
 7             try
 8             {
 9                 while (Console.ReadLine() != "wxy")
10                 {
11                     Console.WriteLine("Wrong KeyWord!");
12 
13                     i++;
14                     if (i >= count)
15                         throw (new Exception("Over 3 times! Quit!"));
16                     Console.WriteLine("Please Input the KeyWord:");
17                 }
18                 Console.WriteLine("Success!");
19             }
20             catch (Exception e)
21             {
22                 Console.WriteLine(e.Message);
23             }            
24             Console.ReadLine();
25 
26             /*
27             Please Input the KeyWord:
28             1
29             Wrong KeyWord!
30             Please Input the KeyWord:
31             2
32             Wrong KeyWord!
33             Please Input the KeyWord:
34             3
35             Wrong KeyWord!
36             Over 3 times! Quit!
37              */
38         }

@5:自定義異常類:

  對於自定義的異常要在出現異常時使用throw關鍵字來引發異常.

  自定義異常類繼承於System.ApplicationException類,該類是區別於異常是系統定義的還是用戶自定義的.

示例4
 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             int age = 209;
 6             try
 7             {
 8                 if (age < 0 || age > 200)
 9                     throw (new MyException("年齡超范圍", age));
10             }
11             catch (MyException ex)
12             {
13                 Console.WriteLine("catch塊: {0}", ex.MyMessage);
14             }
15 
16             Console.WriteLine("age = {0}", age);
17             Console.WriteLine("END!");
18             Console.ReadLine();
19             /*
20             自定義錯誤:
21             年齡不能大於200
22             catch塊: 應用程序中的錯誤。
23             age = 209
24             END!
25              */
26         }
27 
28     }
29     class MyException : ApplicationException
30     {
31         private string myMessage;
32         public string MyMessage
33         {
34             get { return myMessage; }
35             set
36             {
37                 myMessage = Message;
38                 //myMessage = value;       //Message
39             }
40         }
41         public MyException(string str, int value)
42         {
43             MyMessage = str;
44             Console.WriteLine("自定義錯誤:");
45             if (value < 0)
46                 Console.WriteLine("年齡不能小於0");
47             else
48                 Console.WriteLine("年齡不能大於200");
49         }
50     }

 

Reference:

吳曉艷《C#語言程序設計》

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM