日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
C#如何創(chuàng)建用戶自定義異常?

 

概述

異常是在程序執(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 類。

 
 
 
 
  1. using System; 
  2. namespace UserDefinedException 
  3.    class TestTemperature 
  4.    { 
  5.       static void Main(string[] args) 
  6.       { 
  7.          Temperature temp = new Temperature(); 
  8.          try 
  9.          { 
  10.             temp.showTemp(); 
  11.          } 
  12.          catch(TempIsZeroException e) 
  13.          { 
  14.             Console.WriteLine("TempIsZeroException: {0}", e.Message); 
  15.          } 
  16.          Console.ReadKey(); 
  17.       } 
  18.    } 
  19. public class TempIsZeroException: ApplicationException 
  20.    public TempIsZeroException(string message): base(message) 
  21.    { 
  22.    } 
  23. public class Temperature 
  24.    int temperature = 0; 
  25.    public void showTemp() 
  26.    { 
  27.       if(temperature == 0) 
  28.       { 
  29.          throw (new TempIsZeroException("Zero Temperature found")); 
  30.       } 
  31.       else 
  32.       { 
  33.          Console.WriteLine("Temperature: {0}", temperature); 
  34.       } 
  35.    } 

當(dāng)上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:

 
 
 
 
  1. TempIsZeroException: Zero Temperature found 

拋出對象

如果異常是直接或間接派生自 System.Exception 類,您可以拋出一個對象。您可以在 catch 塊中使用 throw 語句來拋出當(dāng)前的對象,如下所示:

 
 
 
 
  1. Catch(Exception e) 
  2.    ... 
  3.    Throw e 

 【編輯推薦】

  1. 光通信發(fā)展為何不如 5G,專家直言:各自為戰(zhàn)
  2. 智慧醫(yī)療邁入快車道,多種智能技術(shù)被看好
  3. Linkerd 2.10(Step by Step)(四) 如何配置外部 Prometheus 實(shí)例
  4. 勒索攻擊頻發(fā)大廠紛紛中招企業(yè)該如何防護(hù)?
  5. IDC發(fā)布《2021 年第一季度中國IT安全硬件市場跟蹤報(bào)告》

新聞名稱:C#如何創(chuàng)建用戶自定義異常?
文章路徑:http://www.dlmjj.cn/article/dpphiij.html