新聞中心
概述
異常是在程序執(zhí)行期間出現(xiàn)的問題。C# 中的異常是對程序運(yùn)行時出現(xiàn)的特殊情況的一種響應(yīng),比如嘗試除以零。異常提供了一種把程序控制權(quán)從某個部分轉(zhuǎn)移到另一個部分的方式。C# 異常處理時建立在四個關(guān)鍵詞之上的:try、catch、finally和throw。

try:一個 try 塊標(biāo)識了一個將被激活的特定的異常的代碼塊。后跟一個或多個 catch 塊。catch:程序通過異常處理程序捕獲異常。catch 關(guān)鍵字表示異常的捕獲。finally:finally 塊用于執(zhí)行給定的語句,不管異常是否被拋出都會執(zhí)行。例如,如果您打開一個文件,不管是否出現(xiàn)異常文件都要被關(guān)閉。throw:當(dāng)問題出現(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);
- }
- }
- }
當(dāng)上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:
- TempIsZeroException: Zero Temperature found
拋出對象
如果異常是直接或間接派生自 System.Exception 類,您可以拋出一個對象。您可以在 catch 塊中使用 throw 語句來拋出當(dāng)前的對象,如下所示:
- Catch(Exception e)
- {
- ...
- Throw e
- }
【編輯推薦】
- 光通信發(fā)展為何不如 5G,專家直言:各自為戰(zhàn)
- 智慧醫(yī)療邁入快車道,多種智能技術(shù)被看好
- Linkerd 2.10(Step by Step)(四) 如何配置外部 Prometheus 實(shí)例
- 勒索攻擊頻發(fā)大廠紛紛中招企業(yè)該如何防護(hù)?
- IDC發(fā)布《2021 年第一季度中國IT安全硬件市場跟蹤報(bào)告》
新聞名稱:C#如何創(chuàng)建用戶自定義異常?
文章路徑:http://www.dlmjj.cn/article/dpphiij.html


咨詢
建站咨詢
