以下代码生成 NullReferenceException
,但不会被 try block 捕获(在 Debug
和 Release
模式下):
using System;
namespace ExceptionTest {
public class Program {
public static void Main(string[] args) {
String text = null;
try {
if (text.Equals("t1")) {
Console.WriteLine("r1");
} else {
Console.WriteLine("r2");
}
} catch(Exception ex) {
Console.WriteLine("Exception catched!");
}
}
}
}
相反,程序中断并突出显示有问题的行:
为什么?
更新:Scott 建议的异常的文本表示:
System.NullReferenceException occurred
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=ExceptionTest
最佳答案
发生这种情况是因为您选中了此框
这会使您的调试器在到达 catch block 之前中断,如果您点击 continue,您会看到它继续进入 catch。如果您取消选中该框,您可以在通过 Debug -> Windows -> Exception Settings
找到的“异常设置”窗口下重新启用它。下拉式菜单。 “公共(public)语言运行时异常”部分包含 NullRefrenceException
选项。
关于c# - 为什么没有捕获异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42308407/