C# 中的 Try-Catch-Finally
C#异常是对程序运行时出现的异常情况的响应,例如试图除以零。
C#异常处理使用以下关键字执行-
try-try块标识激活特定异常的代码块。后面跟着一个或多个catch块。
catch-程序在程序中要处理问题的位置使用异常处理程序捕获异常。catch关键字表示捕获异常。
finally-finally块用于执行一组给定的语句,无论是否抛出异常。例如,如果您打开一个文件,无论是否引发异常,它都必须关闭。
以下是显示如何在C#中处理异常的示例-
示例
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();
}
}
}输出结果上面,我们在try中设置了值,然后在catch中捕获了异常。最后也设置为显示结果-
try {
result = num1 / num2;
} catch (DivideByZeroException e) {
Console.WriteLine("Exception caught: {0}", e);
} finally {
Console.WriteLine("Result: {0}", result);
}