在.NET中,如果catch块中出现故障,将会始终被调用? [英] In .NET, what if something fails in the catch block, will finally always get called?

查看:92
本文介绍了在.NET中,如果catch块中出现故障,将会始终被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  try 
{

}
catch()
{
// code $ here
}
finally
{

}

所以如果catch块中有一个异常,最终会被调用?



如果没有终止,那么catch块之后的代码是否会运行?

解决方案

假设进程没有突然终止(或者当然挂起),finally块将永远执行。



如果没有finally块,捕获的异常块将被抛出堆栈。请注意,导致catch块首次执行的原始异常将会被有效地丢失。



堆栈溢出异常



正如Jared所说,堆栈溢出将导致finally块不被执行。我相信这突然终止了程序,但是我可能是错的。以下是示例代码:

  using System; 

public class Test
{
static void Main()
{
//给堆栈一些东西来打包
int x = 10;
try
{
Main();
Console.WriteLine(x);
}
finally
{
Console.WriteLine(Finally);
}
}
}

结果:


由于StackOverflowException,进程终止。



In a try/catch/finally block like:

try
{

}
catch()
{
   // code fails here
}
finally
{ 

}

So if there is an exception in the catch block, will finally always get called?

What if there is no finally, will the code after the catch block get run?

解决方案

Assuming the process doesn't terminate abruptly (or hang, of course), the finally block will always be executed.

If there's no finally block, the exception from the catch block will just be thrown up the stack. Note that the original exception which caused the catch block to be executed in the first place will be effectively lost.

Stack overflow exceptions

As Jared noted, a stack overflow will cause the finally block not to be executed. I believe this terminates the program abruptly, but I could be wrong. Here's sample code:

using System;

public class Test
{    
    static void Main()
    {
        // Give the stack something to munch on
        int x = 10;
        try
        {
            Main();
            Console.WriteLine(x);
        }
        finally
        {
            Console.WriteLine("Finally");
        }
    }  
}

Results:

Process is terminated due to StackOverflowException.

这篇关于在.NET中,如果catch块中出现故障,将会始终被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆