mee*_*eem 5 c# exception-handling try-catch-finally
可能重复:
最后块没有运行?
我有一个关于c#中finally块的问题.我写了一个小示例代码:
public class MyType
{
public void foo()
{
try
{
Console.WriteLine("Throw NullReferenceException?");
string s = Console.ReadLine();
if (s == "Y")
throw new NullReferenceException();
else
throw new ArgumentException();
}
catch (NullReferenceException)
{
Console.WriteLine("NullReferenceException was caught!");
}
finally
{
Console.WriteLine("finally block");
}
}
}
class Program
{
static void Main(string[] args)
{
MyType t = new MyType();
t.foo();
}
}
Run Code Online (Sandbox Code Playgroud)
据我所知,最后阻塞假设确定性地运行,无论是否抛出异常.现在,如果用户输入"Y" - 抛出NullReferenceException,则执行移动到catch时钟,然后移动到finally块,如我所料.但如果输入是其他东西 - 抛出ArgumentException.没有合适的catch块来捕获这个异常,所以我认为执行应该移动finally块 - 但它没有.有人可以解释一下为什么?
感谢大家 :)
您的调试器可能正在捕获ArgumentException,所以它等待您在进入最终块之前"处理"它.运行你的代码没有附加的调试器(包括你的JIT调试器),它应该命中你的finally块.
要禁用JIT,请转到选项>工具>调试>即时,然后取消选中托管
要调试没有连接的调试器,在Visual Studio中转到Debug> Start Without Debugging(或CTRL + F5)
在程序结束时放置Console.ReadLine()以防止控制台在进入finally块后关闭也会很有帮助.
class Program {
static void Main(string[] args) {
MyType t = new MyType();
t.foo();
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
这是你应该得到的输出:
抛出NullReferenceException?ñ
未处理的异常:System.ArgumentException:值不在预期范围内.
在P:\ Documents\Sandbox\Console\Console\Consol e\Program.cs中的ConsoleSandbox.MyType.foo():第17行
在P:\ Documents\Sandbox\Console\Console\Console\Program.cs中的ConsoleSandbox.Program.Main(String [] args):第31行
终于阻止了
按任意键继续 ...
| 归档时间: |
|
| 查看次数: |
1060 次 |
| 最近记录: |