C#中的final关键字
无论是否引发异常,finally关键字都用作执行给定语句集的块。例如,如果打开文件,则无论是否引发异常,都必须关闭该文件。
语法
以下是语法-
try {
//导致异常的语句
} catch( ExceptionName e1 ) {
//错误处理代码
} catch( ExceptionName e2 ) {
//错误处理代码
} catch( ExceptionName eN ) {
//错误处理代码
} finally {
//要执行的语句
}示例
让我们看一个示例来实现finally块-
using System;
public class Demo {
int result;
Demo() {
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);
}
}
public static void Main(string[] args) {
Demo d = new Demo();
d.division(100, 0);
}
}输出结果
这将产生以下输出-
Exception caught = System.DivideByZeroException: Attempted to divide by zero. at Demo.division(Int32 num1, Int32 num2) in d:\Windows\Temp\n0kebv45.0.cs:line 11 Result = 0
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语