【发布时间】:2016-10-01 08:10:44
【问题描述】:
我有以下 c# 代码:
public class Program
{
static void Main()
{
int i = 123;
string s = "Some string";
object obj = s;
try
{
// Invalid conversion;
i = (int)obj;
// The following statement is not run.
Console.WriteLine("WriteLine at the end of the try block.");
}
finally
{
Console.WriteLine("\n Finally Block executed !!!");
}
}
}
当异常发生时程序崩溃,没有将控制权传递给 finally 块,因为理解必须执行 finally 块来释放在 try 块中获得的资源。
【问题讨论】:
-
从this fiddle 可以看出,这不是真的。提供一个 minimal reproducible example 来证明您的问题。
-
是的,它可以在 dotnetfiddle 上运行,但是当我在 Visual Studio 2013 上运行它时,它会抛出以下异常,而没有通过控制来最终阻止,就像你的情况一样。未处理的异常:System.InvalidCastException:指定的转换无效。在 c:\Users\Kifayat\Desktop\Learn\excepti onHandling\exceptionHandling\Program.cs:line 69 中的 exceptionHandling.Program.Main() 处
-
它仍然会执行它。您可能会看到 Visual Studio 在未处理的异常上中断,这将在 finally 块执行之前。再次点击“运行”,finally 块将执行。
标签: c# exception exception-handling try-catch-finally try-finally