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.