您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“C#怎么創(chuàng)建用戶自定義異?!?,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“C#怎么創(chuàng)建用戶自定義異常”吧!
您也可以定義自己的異常。用戶自定義的異常類是派生自 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 }
到此,相信大家對“C#怎么創(chuàng)建用戶自定義異?!庇辛烁畹牧私?,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。