Computer >> Máy Tính >  >> Lập trình >> C#

Ngoại lệ tùy chỉnh do người dùng xác định trong C #

Các ngoại lệ của C # được đại diện bởi các lớp. Các lớp ngoại lệ trong C # chủ yếu được dẫn xuất trực tiếp hoặc gián tiếp từ lớp System.Exception.

Bạn cũng có thể xác định ngoại lệ của riêng mình. Các lớp ngoại lệ do người dùng định nghĩa có nguồn gốc từ lớp Exception.

Sau đây là một ví dụ -

Ví dụ

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