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);
}热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下