MethodInfo.Invoke中的Uncatcheableexception
我有这个代码调用一个MethodInfo:
try { registrator.Method.Invoke(instance, parameters); } catch{ registrator.FailureType = RegistratorFailureType.ExceptionInRegistrator; //registrator.Exception = e; }
Registrator只是一个MethodInfo包装器,Method属性是MethodInfo对象本身。 参数是和object []和实例是Method的声明类型的正确实例(使用Activator.Create创建)。
方法看起来像这样(我正在测试exception捕获):
class Test : Plugin, ITest { public void Register(IWindow window) { throw new Exception("Hooah"); } }
问题是:exception永远不会被捕获,并且会弹出Visual Studio未捕获的exception气泡。
这是在使用.NET 4.0的VS 2010中
无论如何,问题不在您的代码中。
在“调试/例外”菜单中,删除所有检查。
它应该工作。
你试过这个吗?
在Program.cs中
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
和Run方法的try / catch:
try { Application.Run(new Form1()); } catch (Exception ex) { }
问题不在于您显示的代码。
我试过这个:
void Main() { Test instance = new Test(); object[] parameters = new object[] { null }; MethodInfo method = typeof(Test).GetMethod("Register"); try { method.Invoke(instance, parameters); } catch { Console.Out.WriteLine("Exception"); } } interface ITest { } interface IWindow { } class Plugin { } class Test : Plugin, ITest { public void Register(IWindow window) { throw new Exception("Hooah"); } }
它按预期打印了“例外”。 您需要向我们展示更多代码。
如果我像这样修改代码:
catch(Exception ex) { Console.Out.WriteLine(ex.GetType().Name + ": " + ex.Message); }
然后我得到一个TargetInvocationException,其中InnerException属性是抛出的Exception。
我认为问题是你期望一个特定的exception类型,可能是IOException
,但实际上MethodInfo.Invoke()
会抛出一个TargetInvocationException
:
try { registrator.Method.Invoke(instance, parameters); } catch (TargetInvocationException tie) { // replace IOException with the exception type you are expecting if (tie.InnerException is IOException) { registrator.FailureType = RegistratorFailureType.ExceptionInRegistrator; registrator.Exception = tie.InnerException; } else { // decide what you want to do with all other exceptions — maybe rethrow? throw; // or maybe unwrap and then throw? throw tie.InnerException; } }