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 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始使用
广告