C# finally
C# finally
C# finally 块用于执行重要的代码,无论是否处理异常都将执行这些代码。前面必须有 catch 或 try 块。
C# finally 示例是否处理异常
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
C# finally 示例,如果不处理异常
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