我是asm的新手,现在我想在课堂上为每个方法捕获异常,尝试自己实现并通过谷歌搜索,但失败了,谁能为我写一个完整的例子?
MethodVisitor mv = super.visitMethod(access, name, desc, signature,
exceptions);
mv.visitCode();
Label lTryBlockStart = new Label();
Label lTryBlockEnd = new Label();
Label lCatchBlockStart = new Label();
Label lCatchBlockEnd = new Label();
// set up try-catch block for RuntimeException
mv.visitTryCatchBlock(lTryBlockStart, lTryBlockEnd, lCatchBlockStart,
"java/lang/Exception");
mv.visitLabel(lTryBlockStart);
// code to call the method goes here
// mv.visitVarInsn(ALOAD, 0);
// mv.visitMethodInsn(Opcodes.INVOKESPECIAL, this.name, name, desc);
mv.visitLabel(lTryBlockEnd);
mv.visitJumpInsn(GOTO, lCatchBlockEnd); // when here, no exception was
// thrown, so skip exception
// handler
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitFieldInsn(Opcodes.INVOKESPECIAL, this.name, name, desc);
// exception handler starts here, with RuntimeException stored on the
// stack
mv.visitLabel(lCatchBlockStart);
mv.visitVarInsn(ASTORE, 1); // store the RuntimeException in local
// variable 1
// here we could for example do e.printStackTrace()
mv.visitVarInsn(ALOAD, 1); // load it
mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Exception",
"printStackTrace", "()V");
// exception handler ends here:
mv.visitLabel(lCatchBlockEnd);
mv.visitEnd();`
我无法运行这些代码,每次都会抛出一个奇怪的异常