Uncatcheable exception from MethodInfo.Invoke

前端 未结 4 1818
闹比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: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;
        }
    }
    

提交回复
热议问题