在编程中,有时异常可能会导致错误,从而终止当前方法。但是,该方法可能已经打开了需要关闭的文件或网络。因此,为了克服这类问题,C#提供了一个特殊的关键字,称为finally关键字。它是C#中的保留关键字。
当try / catch块退出执行时,无论导致什么情况,finally块都将执行。它总是执行try块是正常终止还是由于异常终止。 finally块的主要目的是释放系统资源。 finally块位于try / catch块之后。
句法:
try {
// code...
}
// this is optional
catch {
// code..
}
finally
{
// code..
}
重要事项:
- 在C#中,不允许在同一程序中使用多个finally块。
- finally块不包含任何return,continue,break语句,因为它不允许控件离开finally块。
- 您也可以只将try块与try块一起使用,而没有catch块,但是在这种情况下,不会处理任何异常。
- 最终块将在try和catch块之后但在控制权移回其原点之前执行。
范例1:
// C# program to demonstrate finally
using System;
class Geek {
// A method that throws an
// exception and has finally.
// This method will be called
// inside try-catch.
static void A()
{
try {
Console.WriteLine("Inside A");
throw new Exception("Throwing Exception");
}
finally
{
Console.WriteLine("A's finally");
}
}
// This method also calls
// finally. This method
// will be called outside
// try-catch.
static void B()
{
try {
Console.WriteLine("Inside B");
return;
}
finally
{
Console.WriteLine("B's finally");
}
}
// Main Method
public static void Main(String[] args)
{
try {
A();
}
catch (Exception) {
Console.WriteLine("Exception Caught");
}
B();
}
}
输出:
Inside A
A's finally
Exception Caught
Inside B
B's finally
示例2:使用带有处理异常的finally块
// C# program to illustrate the finally
// block with handled exception
using System;
public class GFG {
// Main Method
static public void Main()
{
// variables
int number = 4;
int divisor = 0;
// try block
// This block raise exception
try {
int output = number / divisor;
}
// catch block
// This block handle exception
catch (DivideByZeroException) {
Console.WriteLine("Not possible to divide by zero!");
}
// finally block
// This block release the
// resources of the system
// and this block always executes
finally {
Console.WriteLine("Finally Block!");
}
}
}
输出:
Not possible to divide by zero!
Finally Block!
说明:在上面的示例中,在try块内生成了一个异常(DivideByZeroException),该异常被与try块相关联的catch块捕获。现在,在try-catch块离开执行之后,finally块将执行并释放try-catch块使用的系统资源。
示例3:使用带有未处理异常的finally块
// C# program illustrate the finally
// block with unhandled exception
using System;
public class GFG {
// Main method
static public void Main () {
// variables
int number = 4;
int divisor = 0;
int output;
// In this block exception raise
// Here this exception in unhandled
// due to the absence of catch block
try
{
output = number/divisor;
}
// finally block, this block always
// executes
finally
{
Console.WriteLine("Finally Block!");
}
}
}
输出:
Finally Block!
运行时错误:
Unhandled Exception:
System.DivideByZeroException: Attempted to divide by zero.
at GFG.Main () in :0
[ERROR] FATAL UNHANDLED EXCEPTION: System.DivideByZeroException: Attempted to divide by zero.
at GFG.Main () in :0
说明:在此示例中,在try块内生成了一个异常(DivideByZeroException),但由于没有与try块关联的catch块而无法处理。在这种情况下,当try块退出执行时,finally块将执行并释放系统资源。这意味着finally块不关心是否处理了异常。