如何用C#創(chuàng)建用戶自定義異常淺析
概述
異常是在程序執(zhí)行期間出現(xiàn)的問題。C# 中的異常是對程序運行時出現(xiàn)的特殊情況的一種響應,比如嘗試除以零。異常提供了一種把程序控制權從某個部分轉移到另一個部分的方式。C# 異常處理時建立在四個關鍵詞之上的:try、catch、finally和throw。
try:一個 try 塊標識了一個將被激活的特定的異常的代碼塊。后跟一個或多個 catch 塊。catch:程序通過異常處理程序捕獲異常。catch 關鍵字表示異常的捕獲。finally:finally 塊用于執(zhí)行給定的語句,不管異常是否被拋出都會執(zhí)行。例如,如果您打開一個文件,不管是否出現(xiàn)異常文件都要被關閉。throw:當問題出現(xiàn)時,程序拋出一個異常。使用 throw 關鍵字來完成。
自定義異常
您也可以定義自己的異常。用戶自定義的異常類是派生自 ApplicationException 類。
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);
}
}
}
當上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結果:
TempIsZeroException: Zero Temperature found
拋出對象
如果異常是直接或間接派生自 System.Exception 類,您可以拋出一個對象。您可以在 catch 塊中使用 throw 語句來拋出當前的對象,如下所示:
Catch(Exception e)
{
...
Throw e
}
總結
到此這篇關于如何用C#創(chuàng)建用戶自定義異常的文章就介紹到這了,更多相關C#用戶自定義異常內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Unity的AssetPostprocessor?Model動畫函數(shù)使用案例深究
這篇文章主要介紹了Unity的AssetPostprocessor?Model動畫函數(shù)使用案例的深入解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08

