首页 > 解决方案 > 为什么我不能从构造函数中捕获这个异常?

问题描述

ArgumentNullException在此测试代码中,尽管已处理,为什么测试失败并显示?

        [Test]
        public void ExceptionBehaviorTest()
        {
            // This works. An instance is returned
            var testInstance = (TestClass)Activator.CreateInstance(typeof(TestClass), "Hello World");
            Assert.NotNull(testInstance);

            // This passes. Exception is generated and caught
            Assert.Throws<ArgumentNullException>(() => new TestClass(null));

            try
            {
                // This throws ArgumentNullException but the catch handler is not invoked. This fails the test
                testInstance = (TestClass)Activator.CreateInstance(typeof(TestClass), (string)null);
                Assert.Fail("Should not get here");
            }
            catch (ArgumentNullException)
            {
            }
        }

        private sealed class TestClass
        {
            public TestClass(string arg)
            {
                Argument = arg ?? throw new ArgumentNullException(nameof(arg));
            }

            public string Argument
            {
                get;
            }
        }

如果我在调试器中运行代码,它会在TestClassctor 中停止,表示未处理异常。但是调用函数在堆栈中是可见的,因此问题与在不同线程上执行的某些部分无关。

[背景:在我的实际代码中,我正在迭代一堆类并测试它们是否有一个带有特定参数的 ctor。这是为了防止以后出现运行时错误,因为类是使用依赖注入构造的。]

标签: c#exceptionreflection

解决方案


这是在文档中

目标调用异常

被调用的构造函数抛出异常。

所以你需要抓住TargetInvocationException这种情况,如果你喜欢你也可以使用when,虽然我不确定它对你的测试有多大帮助

catch (TargetInvocationException ex) when (ex.InnerException is ArgumentNullException)
{
     Console.WriteLine("Caught");
}

推荐阅读