C# 中的内置异常

csharpserver side programmingprogramming更新于 2024/9/25 2:37:00

异常是程序执行时出现的问题。以下关键字处理 C# 中的异常:

try

try 块标识激活特定异常的代码块。

Catch

catch 关键字表示捕获异常。

finally

执行一组给定的语句,无论是否引发异常。

throw

当程序中出现问题时,会引发异常。

示例

让我们看一个处理 C# 程序中的错误的示例 −

using System;
namespace MyErrorHandlingApplication {
   class DivNumbers {
      int result;
      DivNumbers() {
         result = 0;
      }
      public void myDivision(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.myDivision(5, 0);
         Console.ReadKey();
      }
   }
}

输出

Result: 0

相关文章