Uncatcheable exception from MethodInfo.Invoke

前端 未结 4 1800
闹比i
闹比i 2020-12-22 09:08

I have this code which Invokes a MethodInfo:

try
{
     registrator.Method.Invoke(instance, parameters);
}
catch{
    registrator.FailureType = RegistratorFa         


        
相关标签:
4条回答
  • 2020-12-22 09:35

    Have you tried this?

    In Program.cs

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

    And a try/catch on the Run method:

    try
    {
        Application.Run(new Form1());
    }
        catch (Exception ex)
    {
    }
    
    0 讨论(0)
  • 2020-12-22 09:42

    The problem is not with the code you're showing.

    I tried this:

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

    It printed "Exception" as expected. You need to show us more code.

    If I modify the code like this:

    catch(Exception ex)
    {
        Console.Out.WriteLine(ex.GetType().Name + ": " + ex.Message);
    }
    

    Then I get a TargetInvocationException, where the InnerException property is your thrown Exception.

    0 讨论(0)
  • 2020-12-22 09:43

    I think the problem is that you are expecting a specific exception type, maybe IOException or something, but actually MethodInfo.Invoke() will throw a 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;
        }
    }
    
    0 讨论(0)
  • 2020-12-22 09:47

    The problem is not in your code anyway.
    In the Debug/Exceptions menu, remove all checks.
    It should work.

    0 讨论(0)
提交回复
热议问题