📅  最后修改于: 2020-10-31 04:05:14             🧑  作者: Mango
C#finally块用于执行重要代码,无论是否处理异常,该代码都将执行。它必须在catch或try块之前。
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");
}
}
输出:
System.DivideByZeroException: Attempted to divide by zero.
Finally block is executed
Rest of the code
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