學習C#異常處理機制

來源:互聯網
上載者:User
異常類型的類別基類 Exception 下存在兩類異常:
  • SystemException派生的預定義公用語言運行庫異常類。

  • ApplicationException派生的使用者定義的應用程式異常類。

Exception 包含很多屬性,可以協助標識異常的代碼位置、類型、協助檔案和原因:StackTrace、InnerException、Message、HelpLink、HResult、Source、TargetSite 和 Data。

 


以下我開始對這幾個屬性開始測試代碼示範如下:

Code

 1 using System;
2
3 namespace Uer_Test
4 {
5 class LableOverflowException : Exception
6 {
7 const string OverflowMessage = "此處引發了一個使用者自訂溢出異常";
8 #region(此處引用的Exception類方法介面備忘)
9 //public Exception(string message, Exception innerException);
10 // 摘要:
11 // 使用指定錯誤訊息和對作為此異常原因的內部異常的引用來
12 // 初始化 System.Exception 類的新執行個體。
13 // 參數:
14 // message:
15 // 解釋異常原因的錯誤訊息。
16 //
17 // innerException:
18 // 導致當前異常的異常;如果未指定內部異常,則是一個 null 引用
19 #endregion
20 public LableOverflowException(string OvererrorMessage, Exception User_Exception)
21 : base(string.Format("{0}-{1}", OverflowMessage, OvererrorMessage), User_Exception)
22 {
23 this.HelpLink = "http://rohelmx.blog.163.com/";
24 this.Source = ".Net異常處理機制.exe";
25 }
26 }
27 class ArrayStringDemo
28 {
29 protected string[] ArrayDemo;
30 protected int Number;
31 public ArrayStringDemo(int index)
32 {
33 ArrayDemo = new String[index];
34 Number = 0;
35 }
36 // 下面的方法數組越界異常被捕獲將拋出一個異常
37 public int Addelement(string newelement)
38 {
39 try
40 {
41 ArrayDemo[Number] = newelement;
42 return Number++;
43 }
44 catch(Exception e)
45 {
46 throw new LableOverflowException(string.Format(@"元素'{0}'不能加入該數組!",newelement),e);
47 }
48 }
49 }
50 class TestExceptionDemo
51 {
52 //建立一個ArrayDemo並強制溢出
53 public static void Main()
54 {
55 ArrayStringDemo ASD = new ArrayStringDemo(4);
56 Console.WriteLine(
57 "示範:\n Exception.Message, \n" +
58 " Exception.HelpLink, \n Exception.Source, \n" +
59 " Exception.StackTrace \n Exception." +
60 "TargetSite \n輸出資訊列表如下:");
61 try
62 {
63 for (int count = 1; ; count++)
64 {
65 ASD.Addelement(string.Format("{0}", count));
66 }
67 }
68 catch (Exception ex)
69 {
70 Console.WriteLine("\nMessage ---\n{0}", ex.Message);
71 Console.WriteLine("\nHelpLink ---\n{0}",ex.HelpLink);
72 Console.WriteLine("\nSource ---\n{0}", ex.Source);
73 Console.WriteLine( "\nStackTrace ---\n{0}", ex.StackTrace);
74 Console.WriteLine("\nTargetSite ---\n{0}", ex.TargetSite);
75 }
76 Console.ReadKey();
77 }
78 }
79 }

try-catch-finally結構官方執行個體: 簡單的解釋一下:其中包含了以一個常規catch子句(既不指定異常類型也不指定異常變數名的catch子句)。 一個try語句最多隻能有一個只能包含一個catch子句,而且如果存在他必須是最後一個catch子句,他被認為是任何異常類型的匹配項。
 1 // try_catch_finally.cs
2 using System;
3 public class EHClass
4 {
5 static void Main()
6 {
7 try
8 {
9 Console.WriteLine("Executing the try statement.");
10 throw new NullReferenceException();
11 }
12 catch (NullReferenceException e)
13 {
14 Console.WriteLine("{0} Caught exception #1.", e);
15 }
16 catch
17 {
18 Console.WriteLine("Caught exception #2.");
19 }
20 finally
21 {
22 Console.WriteLine("Executing finally block.");
23 }
24 }
25 }
26
27
28 --------------------------------------------------------------------------------
下面我對這段程式的關鍵區段做一剖析:  catch (NullReferenceException e)在這段代碼中如果不指定異常變數名(此處是e),那麼這個程式僅僅是捕獲了NullReferenceException異常,並進行了處理,但是它將不會顯示異常資訊。但是當我們指定了異常變數名(此處是e),這裡的示範便是這種情況,這樣可以進一步顯示異常資訊(包括常規的StackTrace、Message、Source、TargetSite ).下面的代碼我示範一下異常的嵌套和跳轉處理機制,很簡單,一目瞭然,不在在做說明
Code

 1 using System;
2
3 namespace 示範
4
5 {
6 class Test
7 {
8 static void F()
9 {
10 throw new Exception("捕獲內層異常\n");//拋出異常
11 }
12 static void Main(string[] args)
13 {
14
15 try
16 {
17 try
18 {
19 F();
20 goto label;
21 }
22 catch (Exception e)//捕獲內層異常
23 {
24 Console.WriteLine(e.Message);
25 }
26 finally
27 {
28 throw new Exception("內部Finally塊引發新的異常\n");
29 Console.WriteLine("內層異常處理此處不會進行\n");
30 //此行不執行
31 }
32 }
33 catch (Exception ex)
34 {
35 Console.WriteLine(ex.Message);
36 }
37 finally
38 {
39 Console.WriteLine("異常轉移到外層處理完畢!\n");
40 }
41 label:
42 Console.WriteLine("此處goto語句跳出try語句必須在finally塊執行完後執行。");
43 Console.ReadKey();
44 }
45 }
46 }
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.