【发布时间】:2020-10-22 12:30:13
【问题描述】:
Here微软说:
"通过使用 finally 块,您可以清理任何资源 在 try 块中分配,即使出现异常也可以运行代码 发生在 try 块中。”
并清楚地使用此示例来支持该想法:
public class ThrowTestA
{
static void Main()
{
int i = 123;
string s = "Some string";
object obj = s;
try
{
// Invalid conversion; obj contains a string, not a numeric type.
i = (int)obj;
// The following statement is not run.
Console.WriteLine("WriteLine at the end of the try block.");
}
finally
{
// To run the program in Visual Studio, type CTRL+F5. Then
// click Cancel in the error dialog.
Console.WriteLine("\nExecution of the finally block after an unhandled\n" +
"error depends on how the exception unwind operation is triggered.");
Console.WriteLine("i = {0}", i);
}
}
// Output:
// Unhandled Exception: System.InvalidCastException: Specified cast is not valid.
//
// Execution of the finally block after an unhandled
// error depends on how the exception unwind operation is triggered.
// i = 123
}
但是当我将它复制到我的 .Net-Core 控制台时,它最终没有执行,也没有最终返回我所期望的输出,根据微软所说!它在下面返回,我不知道为什么!
我知道我们可以简单地使用 try..catch 块来解决问题。我就是想知道这个与微软的样本和我的经历的矛盾!
【问题讨论】:
-
我做到了,但没有任何改变
-
在
try {}和finally {}部分之间添加一个catch {}块。 -
@imsmn 我知道,而且很简单!但我刚刚调查了 finally 块行为。为什么我们必须使用它?我们可以简单地删除它并在 catch 之后做任何我们想做的事情!喜欢免费资源等