c# - 为什么没有捕获异常?

标签 c# exception nullreferenceexception

以下代码生成 NullReferenceException ,但不会被 try block 捕获(在 DebugRelease 模式下):

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!");
            }
        }
    }
}

相反,程序中断并突出显示有问题的行:

enter image description here

为什么?

更新:Scott 建议的异常的文本表示:
System.NullReferenceException occurred
  HResult=-2147467261
  Message=Object reference not set to an instance of an object.
  Source=ExceptionTest

最佳答案

发生这种情况是因为您选中了此框

enter image description here

这会使您的调试器在到达 catch block 之前中断,如果您点击 continue,您会看到它继续进入 catch。如果您取消选中该框,您可以在通过 Debug -> Windows -> Exception Settings 找到的“异常设置”窗口下重新启用它。下拉式菜单。 “公共(public)语言运行时异常”部分包含 NullRefrenceException选项。

enter image description here

关于c# - 为什么没有捕获异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42308407/

相关文章:

windows-phone-7 - 不小心更改了项目名称

c# - 为什么额外的异步操作使我的代码比操作根本没有发生时更快?

c# - 为什么 GetType() 为 Nullable<DateTime> 返回 DateTime 类型

c# - 打开文件对话框,多个 Excel 扩展的一个过滤器?

c# - ThrowUnobservedTaskExceptions 不工作

c# - 通用函数

c# - 如何检查字符串是否为空并在同一行中分配其值

c# - 进行 DPI 缩放的简单方法?

java - Android加密 "pad block corrupted"异常

iOS : Background Thread Exceptions Not Crashing