不同语言的语法会有所不同,但这是一个一般性问题。
这和……有什么区别?
try
{
Console.WriteLine("Executing the try statement.");
throw new NullReferenceException();
}
catch (NullReferenceException e)
{
Console.WriteLine("{0} Caught exception #1.", e);
}
finally
{
Console.WriteLine("Executing finally block.");
}还有这个..。
try
{
Console.WriteLine("Executing the try statement.");
throw new NullReferenceException();
}
catch (NullReferenceException e)
{
Console.WriteLine("{0} Caught exception #1.", e);
}
Console.WriteLine("Executing finally block.");我一直看到它被使用,所以我认为最后使用它有一个很好的理由,但我不能弄清楚它与仅仅将代码放在语句后面有什么不同,因为它仍然会运行。
有没有最终不能运行的场景?
发布于 2013-05-23 10:37:26
在您的示例中,这并没有太大的不同。
不过,想象一下:
try
{
Console.WriteLine("Executing the try statement.");
throw new NullReferenceException();
}
catch (SomeOtherException e)
{
Console.WriteLine("{0} Caught exception #1.", e);
}
finally
{
Console.WriteLine("Executing finally block.");
}
Console.WriteLine("Executing stuff after try/catch/finally.");在这种情况下,catch不会捕获错误,因此在整个try/ catch /finally之后的任何内容都将永远不会到达。但是,finally块仍将运行。
发布于 2013-05-23 10:37:42
try
{
throw new Exception("Error!");
}
catch (Exception ex)
{
throw new Exception(ex, "Rethrowing!");
}
finally
{
// Will still run even through the catch kicked us out of the procedure
}
Console.WriteLine("Doesn't execute anymore because catch threw exception");发布于 2013-05-23 10:42:34
这真的要看情况了--其他一些答案有很好的理由使用Finally块。但我认为最好的原因是因为您正在进行异常处理。您在Finally块中所做的事情通常涉及清理资源以确保正确继续,而不管是否抛出异常-对我来说,这仍然是异常处理的一部分,至少是“尝试某些东西”操作的一部分。
Finally作用域强调了这样一个事实,即它的代码中包含了在发生异常时需要特别注意的内容。
https://stackoverflow.com/questions/16704729
复制相似问题