C# 中的使用者自定義異常


C# 異常由類表示。C# 中的異常類主要直接或間接地派生自 System.Exception 類。

您還可以在定義你自己的異常。使用者定義的異常類派生自 Exception 類。

下面是一個示例 −

示例

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: 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);
      }
   }
}

更新於:2020-6-21

383 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始使用
廣告
© . All rights reserved.