代码之家  ›  专栏  ›  技术社区  ›  Matěj Zábský

来自的不可调度异常MethodInfo.调用

  •  0
  • Matěj Zábský  · 技术社区  · 15 年前

    我有一个调用MethodInfo的代码:

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

    注册器只是一个MethodInfo包装器,Method属性是MethodInfo对象本身。参数是和对象[],实例是方法声明类型的正确实例(使用激活器。创建).

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

    问题是:异常永远不会被捕获,VisualStudio未捕获的异常气泡会弹出。

    这是VS2010中的.NET4.0版本

    4 回复  |  直到 15 年前
        1
  •  1
  •   Behrooz    15 年前

    问题不在代码中。
    在“调试/异常”菜单中,删除所有检查。
    应该有用。

        2
  •  0
  •   Jérémie Bertrand Alex Kumbhani    15 年前

    在程序.cs

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

    try
    {
        Application.Run(new Form1());
    }
        catch (Exception ex)
    {
    }
    
        3
  •  0
  •   Lasse V. Karlsen    15 年前

    问题不在于你展示的代码。

    我试过这个:

    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);
    }
    

        4
  •  0
  •   Timwi    15 年前

    我认为问题在于,您可能需要一个特定的异常类型 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;
        }
    }