如何用C#創(chuàng)建用戶自定義異常淺析
概述
異常是在程序執(zhí)行期間出現(xiàn)的問題。C# 中的異常是對程序運行時出現(xiàn)的特殊情況的一種響應(yīng),比如嘗試除以零。異常提供了一種把程序控制權(quán)從某個部分轉(zhuǎn)移到另一個部分的方式。C# 異常處理時建立在四個關(guān)鍵詞之上的:try、catch、finally和throw。
try:一個 try 塊標識了一個將被激活的特定的異常的代碼塊。后跟一個或多個 catch 塊。catch:程序通過異常處理程序捕獲異常。catch 關(guān)鍵字表示異常的捕獲。finally:finally 塊用于執(zhí)行給定的語句,不管異常是否被拋出都會執(zhí)行。例如,如果您打開一個文件,不管是否出現(xiàn)異常文件都要被關(guān)閉。throw:當問題出現(xiàn)時,程序拋出一個異常。使用 throw 關(guān)鍵字來完成。
自定義異常
您也可以定義自己的異常。用戶自定義的異常類是派生自 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)生下列結(jié)果:
TempIsZeroException: Zero Temperature found
拋出對象
如果異常是直接或間接派生自 System.Exception 類,您可以拋出一個對象。您可以在 catch 塊中使用 throw 語句來拋出當前的對象,如下所示:
Catch(Exception e)
{
...
Throw e
}
總結(jié)
到此這篇關(guān)于如何用C#創(chuàng)建用戶自定義異常的文章就介紹到這了,更多相關(guān)C#用戶自定義異常內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#使用SqlServer作為日志數(shù)據(jù)庫的設(shè)計與實現(xiàn)
這篇文章主要給大家介紹了關(guān)于C#使用SqlServer作為日志數(shù)據(jù)庫的設(shè)計與實現(xiàn)的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01

