使用示例在 C# 中自定義異常


異常是在程式執行期間出現的問題。C# 異常是對程式執行時出現的異常情況的響應,例如嘗試除以零。

定義自己的異常。使用者自定義的異常類派生自 Exception 類。

以下是一個示例 −

示例

using System;

namespace UserDefinedException {
   class TestFitness {
      static void Main(string[] args) {
         Fitness f = new Fitness();
         try {
            f.showResult();
         } catch(FitnessTestFailedException e) {
            Console.WriteLine("User defined exception: {0}", e.Message);
         }
         Console.ReadKey();
      }
   }
}

public class FitnessTestFailedException: Exception {
   public FitnessTestFailedException(string message): base(message) {
   }
}

public class Fitness {
   int points = 0;

   public void showResult() {
     
      if(points < 110) {
         throw (new FitnessTestFailedException("Player failed the fitness test!"));
      } else {
         Console.WriteLine("Player passed the fitness test!");
      }
   }
}

以上,我們建立了一個使用者自定義的異常 −

public class FitnessTestFailedException: Exception {
   public FitnessTestFailedException(string message): base(message) {
}

更新於: 2020 年 6 月 21 日

5k+ 瀏覽量

開啟你的職業生涯

透過完成課程獲取認證

開始學習
廣告
© . All rights reserved.