繁体   English   中英

如何使用 try catch 处理 C# 中的反射异常(method.invoke)

[英]How to handle Exception in Reflection(method.invoke) in C# with try catch

当从调用的方法抛出异常时,它无法捕获并抛出异常。

`try
{
     Type type = Type.GetType("abc");
     Object obj = Activator.CreateInstance(type);
     MethodInfo methodInfo = type.GetMethod("xyz");
     object[] parameters = { new object[] { Json } };
     response = (methodInfo.Invoke(obj, parameters));
}
catch
{
     throw;
}
`

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

try
{
     Type type = Type.GetType("abc");
     Object obj = Activator.CreateInstance(type);
     MethodInfo methodInfo = type.GetMethod("xyz");
     object[] parameters = { new object[] { Json } };
     response = (methodInfo.Invoke(obj, parameters));
}
catch (Exception ex)
{
     Debug.WriteLine(ex.Message);
}

使用反射从对Invoke()的方法调用中引发的异常是System.Reflection.TargetInvocationException的包装异常实例。 您要处理的实际异常将在InnerException中。 并且不要忘记使用Debug-> Exception->允许在Visual Studio中引发异常

try
{
 Type type = Type.GetType("abc");
 Object obj = Activator.CreateInstance(type);
 MethodInfo methodInfo = type.GetMethod("xyz");
 object[] parameters = { new object[] { Json } };
 response = (methodInfo.Invoke(obj, parameters));
}
catch (TargetInvocationException ex)
{
    ex = ex.InnerException; // ex now stores the original exception
}

检查response.Exception?.InnerException

try
{
    Type type = Type.GetType("abc");
    Object obj = Activator.CreateInstance(type);
    MethodInfo methodInfo = type.GetMethod("xyz");
    object[] parameters = { new object[] { Json } };
    response = (methodInfo.Invoke(obj, parameters));
 
    if(response != null && response.Exception?.InnerException is Exception){
        //this is an exception from reflection
        throw response.Exception?.InnerException;
    }
}
catch (Exception ex){
    throw;
}

暂无
暂无

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

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