无法从 Activator.CreateInstance 捕获异常
好吧,我承认这段代码对你来说看起来很奇怪,那是因为它很奇怪。这只是重现行为的代码,而不是我想要使用的代码。
class Program
{
static void Main(string[] args)
{
try
{
Activator.CreateInstance(typeof(Func<int>), new object[] { new object(), IntPtr.Zero });
}
catch
{
Console.WriteLine("This won't print!");
}
Console.Write("Actually this will not print either!");
Console.ReadLine();
}
}
无论我尝试捕获哪种异常类型(据我所知,实际抛出的异常是 ArgumentException),catch 块内的代码都不会执行。实际上执行只会在 Activator.CreateInstance 行停止。
OK, I admit it this code will just look weird to you, and that's because it is weird. This is just code to reproduce the behavior, not code I want to use.
class Program
{
static void Main(string[] args)
{
try
{
Activator.CreateInstance(typeof(Func<int>), new object[] { new object(), IntPtr.Zero });
}
catch
{
Console.WriteLine("This won't print!");
}
Console.Write("Actually this will not print either!");
Console.ReadLine();
}
}
No matter what exception type I try to catch (the actual exception thrown is an ArgumentException as far as I can tell) the code inside the catch block will not execute. Actually execution will just stop at the Activator.CreateInstance-line.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您已经用该代码轰炸了 CLR。感人的。实际的事故是垃圾收集堆的损坏,它由 ExecutionEngineException 发出信号。显然,损坏程度足以阻止 CLR 执行异常处理程序。
您可以在 connect.microsoft.com 上报告此问题。但是,该错误在 .NET 4.0 中得到修复,它会生成正确的异常,ArgumentNullException,“值不能为空,参数名称:方法”。解决方法很明显,当需要非空字符串时不要传递 IntPtr.Zero。
You've bombed the CLR with that code. Impressive. The actual mishap is corruption of the garbage collected heap, it is signaled with an ExecutionEngineException. Apparently the damage is extensive enough to prevent the CLR from executing the exception handler.
You can report this at connect.microsoft.com. However, the bug is fixed in .NET 4.0, it generates the proper exception, ArgumentNullException, "Value cannot be null, Parameter name: method". The workaround is obvious, don't pass IntPtr.Zero when it expects a non-null string.
当我在 .NET 3.5 中运行此代码时,我收到一个 ExecutionEngineException 异常。当运行时抛出此异常时,它类似于调用Environment.FailFast。显然这是堆上内存损坏的症状。
当我将示例代码切换到以下内容时,就实现了正确的行为。
我很清楚这带来的问题多于答案......:)
When I run this code in .NET 3.5 I get a
ExecutionEngineException
. When the runtime throws this exception it is similar to callingEnvironment.FailFast
. Apparently this is a symptom of memory corruption on the heap.When I switch your example code to the following the correct behavior is achieved.
I am well aware that this brings up more questions than answers... :)