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

Các ngoại lệ do người dùng xác định trong C # là gì?

Giống như bất kỳ ngôn ngữ lập trình nào khác, trong C #, bạn có thể dễ dàng tạo một ngoại lệ do người dùng xác đị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. Các ngoại lệ tùy chỉnh là những gì chúng tôi gọi là các ngoại lệ do người dùng xác định.

Trong ví dụ dưới đây, ngoại lệ được tạo không phải là ngoại lệ cài sẵn; nó là một ngoại lệ tùy chỉnh -

TempIsZeroException

Bạn có thể thử chạy đoạn mã sau để tìm hiểu cách tạo ngoại lệ do người dùng xác định trong C # -

Ví dụ

using System;

namespace Demo {
   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);
      }
   }
}

Đầu ra

TempIsZeroException: Zero Temperature found