Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 最后,在catch之前执行块_C#_Try Catch - Fatal编程技术网

C# 最后,在catch之前执行块

C# 最后,在catch之前执行块,c#,try-catch,C#,Try Catch,据我所知,try-catch-finally语句,在捕获异常之后,最终执行块。当函数抛出异常时,这是如何应用的,如下面的示例所示。若在finally块中释放了一些资源,而这些资源在初始异常下无法释放,那个该怎么办。这是否意味着finally块抛出新的(另一个)异常,覆盖原始异常 我知道,您可以捕获可能在调用堆栈上层的try finally语句的try块中抛出的异常。也就是说,可以在调用包含try finally语句()的方法的方法中捕获异常 输出: foo foo's finally calle

据我所知,try-catch-finally语句,在捕获异常之后,最终执行块。当函数抛出异常时,这是如何应用的,如下面的示例所示。若在finally块中释放了一些资源,而这些资源在初始异常下无法释放,那个该怎么办。这是否意味着finally块抛出新的(另一个)异常,覆盖原始异常

我知道,您可以捕获可能在调用堆栈上层的try finally语句的try块中抛出的异常。也就是说,可以在调用包含try finally语句()的方法的方法中捕获异常

输出:

foo
foo's finally called
Exception caught
据我所知,试着抓住最后一句话,就在之后 异常被捕获,最后执行块

不,那是错的

finally
块在执行了适用的
catch
子句块之后执行,或者如果不存在适用的
catch
,则在抛出异常之后立即执行。但是,这仅适用于同一
try
块上的
catch
finally
——如果传播了异常,
finally
将在调用堆栈更上层的任何
catch
和/或
finally
之前运行

当函数抛出异常时,这是如何应用的,例如 下面

调用
foo
,它抛出,最后执行其
块。由于没有
catch
,因此异常会传播并在
main
中捕获

如果在finally块中释放了一些资源,那么会怎么样 无法创建异常

我不明白这个问题

这是否意味着最后block抛出新的(另一个)异常, 覆盖原始异常


是的,当您使用try catch finally时,.

。 如果您的代码出现任何错误,那么它将首先捕获,然后最后捕获。 如果您的代码没有抛出任何错误,那么它将最终调用finally,然后进一步执行


用一个很好的例子进行解释。

这基本上就是您要做的:

 static void Main(string[] args)
 {
   try
   {
       try   
       {
          Console.WriteLine("foo");
          throw new Exception("exception");   //error occurs here
       }   
       finally   //will execute this as it is the first exception statement
       {
           Console.WriteLine("foo's finally called");   
       }   
    }
    catch (Exception e)  // then this
    {
       Console.WriteLine("Exception caught");
    }
 }

我还应该补充一点,不管try和catch块中发生什么情况,finally块中的代码都会执行

try和finally语句嵌入到主方法的try中,不管您在它前面抛出异常,finally
都会被执行。相关:另外,评论一下这是否意味着finally块抛出新的异常(另一个)异常,覆盖原始异常。是的,最后一个异常将覆盖(原始)第一个异常。@TheDutchMan:谢谢,我已经扩展了答案,并包括了这些信息。
 static void Main(string[] args)
 {
   try
   {
       try   
       {
          Console.WriteLine("foo");
          throw new Exception("exception");   //error occurs here
       }   
       finally   //will execute this as it is the first exception statement
       {
           Console.WriteLine("foo's finally called");   
       }   
    }
    catch (Exception e)  // then this
    {
       Console.WriteLine("Exception caught");
    }
 }