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-06-21

383 次瀏覽

開啟你的職業生涯

透過完成課程來獲得認證

開始
廣告
© . All rights reserved.