如何在注入的try catch处理程序中多次访问Exception变量
本文关键字:访问 变量 Exception 程序 处理 注入 catch try | 更新日期: 2023-09-27 18:03:28
我正在使用Mono添加一个围绕方法体的try catch块。塞西尔
一切都很顺利,即使我可以在catch块中调用带有捕获异常exception1参数的方法,因为看起来exception1值在堆栈的顶部。
然而,在调用值从堆栈中删除后,如果我想以exception1作为参数调用其他方法,我不知道如何在调用前访问它。
所以下面的代码是工作的,我只是不知道如何在catch块中调用另一个方法,将捕获的异常值作为参数。
var statementInTheCatchBlock = il.Create(OpCodes.Call, module.Import(typeof(AnyType).GetMethod("AnyMethod", new[] { typeof(Exception) })));
var ret = il.Create(OpCodes.Ret);
var leave = il.Create(OpCodes.Leave, ret);
il.InsertAfter(method.Body.Instructions.Last(), statementInTheCatchBlock);
il.InsertAfter(statementInTheCatchBlock, leave);
il.InsertAfter(leave, ret);
var handler = new ExceptionHandler(ExceptionHandlerType.Catch)
{
TryStart = method.Body.Instructions.First(),
TryEnd = statementInTheCatchBlock,
HandlerStart = statementInTheCatchBlock,
HandlerEnd = ret,
CatchType = module.Import(typeof(Exception)),
};
method.Body.ExceptionHandlers.Add(handler);
提前致谢
我终于找到了。关键是定义一个自己的变量,并在catch块的第一条指令中将eval堆栈的顶部存储在这个变量中:
var exceptionVariable = new VariableDefinition("e", method.Module.Import(typeof (Exception)));
method.Body.Variables.Add(exceptionVariable);
var last = method.Body.Instructions.Last();
Instruction tryEnd;
il.InsertAfter(last, tryEnd = last = il.Create(OpCodes.Stloc_S, exceptionVariable));
il.InsertAfter(last, last = il.Create(OpCodes.Ldloc_S, exceptionVariable));
il.InsertAfter(last, last = anyCallInstructionWithExceptionParamter);
il.InsertAfter(last, last = il.Create(OpCodes.Ldloc_S, exceptionVariable));
il.InsertAfter(last, last = otherCallInstructionWithExceptionParamter);
il.InsertAfter(last, last = leave);
il.InsertAfter(last, ret);
var handler = new ExceptionHandler(ExceptionHandlerType.Catch)
{
TryStart = method.Body.Instructions.First(),
TryEnd = tryEnd,
HandlerStart = tryEnd,
HandlerEnd = ret,
CatchType = module.Import(typeof (Exception)),
};
感谢所有花时间在这上面的人(我花了3个小时)