C#如何創(chuàng)建用戶自定義異常?
概述
異常是在程序執(zhí)行期間出現(xiàn)的問(wèn)題。C# 中的異常是對(duì)程序運(yùn)行時(shí)出現(xiàn)的特殊情況的一種響應(yīng),比如嘗試除以零。異常提供了一種把程序控制權(quán)從某個(gè)部分轉(zhuǎn)移到另一個(gè)部分的方式。C# 異常處理時(shí)建立在四個(gè)關(guān)鍵詞之上的:try、catch、finally和throw。
try:一個(gè) try 塊標(biāo)識(shí)了一個(gè)將被激活的特定的異常的代碼塊。后跟一個(gè)或多個(gè) catch 塊。catch:程序通過(guò)異常處理程序捕獲異常。catch 關(guān)鍵字表示異常的捕獲。finally:finally 塊用于執(zhí)行給定的語(yǔ)句,不管異常是否被拋出都會(huì)執(zhí)行。例如,如果您打開(kāi)一個(gè)文件,不管是否出現(xiàn)異常文件都要被關(guān)閉。throw:當(dāng)問(wèn)題出現(xiàn)時(shí),程序拋出一個(gè)異常。使用 throw 關(guān)鍵字來(lái)完成。
自定義異常
您也可以定義自己的異常。用戶自定義的異常類(lèi)是派生自 ApplicationException 類(lèi)。
- using System;
- namespace UserDefinedException
- {
- class TestTemperature
- {
- static void Main(string[] args)
- {
- Temperature temp = new Temperature();
- try
- {
- temp.showTemp();
- }
- catch(TempIsZeroException e)
- {
- Console.WriteLine("TempIsZeroException: {0}", e.Message);
- }
- Console.ReadKey();
- }
- }
- }
- public class TempIsZeroException: ApplicationException
- {
- public TempIsZeroException(string message): base(message)
- {
- }
- }
- public class Temperature
- {
- int temperature = 0;
- public void showTemp()
- {
- if(temperature == 0)
- {
- throw (new TempIsZeroException("Zero Temperature found"));
- }
- else
- {
- Console.WriteLine("Temperature: {0}", temperature);
- }
- }
- }
當(dāng)上面的代碼被編譯和執(zhí)行時(shí),它會(huì)產(chǎn)生下列結(jié)果:
- TempIsZeroException: Zero Temperature found
拋出對(duì)象
如果異常是直接或間接派生自 System.Exception 類(lèi),您可以拋出一個(gè)對(duì)象。您可以在 catch 塊中使用 throw 語(yǔ)句來(lái)拋出當(dāng)前的對(duì)象,如下所示:
- Catch(Exception e)
- {
- ...
- Throw e
- }
【編輯推薦】