繁体   English   中英

MethodInfo.Invoke的无法捕获的异常

[英]Uncatcheable exception from MethodInfo.Invoke

我有调用MethodInfo的这段代码:

try
{
     registrator.Method.Invoke(instance, parameters);
}
catch{
    registrator.FailureType = RegistratorFailureType.ExceptionInRegistrator;
    //registrator.Exception = e;
}

Registrator只是一个MethodInfo包装器,Method属性是MethodInfo对象本身。 参数是and object [],instance是方法的声明类型的正确实例(使用Activator.Create创建)。

该方法如下所示(我正在测试异常捕获):

class Test : Plugin, ITest
{
    public void Register(IWindow window)
    {
        throw new Exception("Hooah");
    }
}

问题是:永远不会捕获到异常,并且会弹出Visual Studio的未捕获异常气泡。

这是在带有.NET 4.0的VS 2010中

无论如何,问题不在您的代码中。
在“调试/异常”菜单中,删除所有检查。
它应该工作。

你有尝试过吗?

在Program.cs中

Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

并尝试/抓住Run方法:

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属性是引发的异常。

我认为问题在于您期望使用特定的异常类型,也许是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;
    }
}

暂无
暂无

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

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