C# 中的 finally 关键字
finally 关键字用作块以执行给定的一组语句,无论是否抛出异常。例如,如果您打开一个文件,无论是否引发异常都必須关闭它。
语法
以下是语法:
try {
// statements causing exception
} catch( ExceptionName e1 ) {
// error handling code
} catch( ExceptionName e2 ) {
// error handling code
} catch( ExceptionName eN ) {
// error handling code
} finally {
// statements to be executed
}示例
讓我們看一个实现 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
0kebv45.0.cs:line 11 Result = 0
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP