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

Làm thế nào để nắm bắt phép chia cho ngoại lệ 0 trong C #?


System.DivideByZeroException là một lớp xử lý các lỗi sinh ra từ việc chia cổ tức bằng không.

Ví dụ

Hãy để chúng tôi xem một ví dụ -

using System;

namespace ErrorHandlingApplication {
   class DivNumbers {
      int result;

      DivNumbers() {
         result = 0;
      }
      public void division(int num1, int num2) {
         try {
            result = num1 / num2;
         } catch (DivideByZeroException e) {
            Console.WriteLine("Exception caught: {0}", e);
         } finally {
            Console.WriteLine("Result: {0}", result);
         }
      }
      static void Main(string[] args) {
         DivNumbers d = new DivNumbers();
         d.division(25, 0);
         Console.ReadKey();
      }
   }
}

Đầu ra

Các giá trị được nhập ở đây là num1 / num2 -

result = num1 / num2;

Ở trên, nếu num2 được đặt thành 0, thì SplitByZeroException sẽ bị bắt vì chúng tôi đã xử lý ngoại lệ ở trên.