前段时间在使用反射机制动态调用函数(通过MethodInfo.Invoke)时,发现无法捕获被调用函数抛出的异常。研究后发现,被调用函数抛出的异常被TargetInvocationException包装了。
- 可以通过以下方法处理被调用函数抛出的自定义异常:
catch (System.Reflection.TargetInvocationException ex)
{
if (ex.InnerException != null)
{
Exception exTmp = ex.InnerException;
if (exTmp is HoundException)
{
LogFile.ErrorFormat("Msg: {0}, Code: {1}", exTmp.Message, ((HoundException)exTmp).ErrorCode);
}
}
}
- 另外还可以使用代理的方法,被调用函数的异常不会被包装,代码看上去更舒服一些。
时间关系没有测试,暂时记录下来,下次需要的时候可以试试。
class Program
{
static void Main()
{
DelegateApproach();
MethodInfoApproach();
}
static void DelegateApproach()
{
try
{
Action action = (Action)Delegate.CreateDelegate
(typeof(Action), GetMethodInfo());
action();
}
catch (NotImplementedException nie)
{
}
}
static void MethodInfoApproach()
{
try
{
GetMethodInfo().Invoke(null, new object[0]);
}
catch (TargetInvocationException tie)
{
if (tie.InnerException is NotImplementedException)
{
}
}
}
static MethodInfo GetMethodInfo()
{
return typeof(Program)
.GetMethod("TestMethod", BindingFlags.NonPublic | BindingFlags.Static);
}
static void TestMethod()
{
throw new NotImplementedException();
}
}