繁体   English   中英

为什么我不能从构造函数中捕获这个异常?

[英]Why can't I catch this exception from a constructor?

在这个测试代码中,为什么测试失败并出现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;
            }
        }

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

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

这是在文档

目标调用异常

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

因此,您需要在这种情况下捕获TargetInvocationException ,如果您愿意,也可以使用when虽然我不确定它对您的测试有多大帮助

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM