C# 中有哪些自定義異常?


與任何其他程式語言一樣,在 C# 中,你可以輕鬆地建立使用者定義的異常。使用者定義的異常類派生自 Exception 類。我們稱使用者定義的異常為自定義異常。

在以下示例中,建立的異常不是內建異常,而是一個自定義異常 -

TempIsZeroException

你可以嘗試執行以下程式碼,瞭解如何在 C# 中建立使用者定義的異常。

示例

 

using System;

namespace Demo {
   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: Exception {
   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);
      }
   }
}

這將生成以下輸出 -

輸出

TempIsZeroException: Zero Temperature found

更新於: 20-06-2020

608 次瀏覽

開啟你的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.