C#finally块用于执行重要代码,无论是否处理异常,该代码都将执行。必须在catch或try块之前。
C#最终示例,如果处理了异常
using System;
public class ExExample
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int x = a / b;
}
catch (Exception e) { Console.WriteLine(e);
}
finally { Console.WriteLine("Finally block is executed");
}
Console.WriteLine("Rest of the code");
}
}
【C# finally块】输出:
System.DivideByZeroException: Attempted to divide by zero.
Finally block is executed
Rest of the code
如果未处理异常,C#最终示例
using System;
public class ExExample
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int x = a / b;
}
catch (NullReferenceException e) { Console.WriteLine(e);
}
finally { Console.WriteLine("Finally block is executed");
}
Console.WriteLine("Rest of the code");
}
}
输出:
Unhandled Exception: System.DivideBy
推荐阅读
- C#文件流
- C# try-catch用法
- C#异常处理
- C#字符串
- C# StreamReader用法
- C# StreamWriter用法
- C#系统异常
- C#已检查和未检查
- C#名称空间namespace