Try-catch blocks in ASM use Label objects to define the protected region and handler entry point:
import org.objectweb.asm.*;
public class TryCatchExample { public static void main(String[] args) throws Exception { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); cw.visit(Opcodes.V11, Opcodes.ACC_PUBLIC, "Example", null, "java/lang/Object", null);
markdown Copy
MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "safeDivide" , "(II)I" , null , null ) ;
mv.visitCode() ;
Label tryStart = new Label() ;
Label tryEnd = new Label() ;
Label handler = new Label() ;
Label after = new Label() ;
mv.visitLabel(tryStart ) ;
mv.visitVarInsn(Opcodes.ILOAD, 1) ;
mv.visitVarInsn(Opcodes.ILOAD, 2) ;
mv.visitInsn(Opcodes.IDIV) ;
mv.visitInsn(Opcodes.IRETURN) ;
mv.visitLabel(tryEnd ) ;
mv.visitLabel(handler ) ;
mv.visitVarInsn(Opcodes.ASTORE, 3) ;
mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System" , "out" , "Ljava/io/PrintStream;" ) ;
mv.visitVarInsn(Opcodes.ALOAD, 3) ;
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Throwable" , "getMessage" , "()Ljava/lang/String;" , false ) ;
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream" , "println" , "(Ljava/lang/String;)V" , false ) ;
mv.visitInsn(Opcodes.ICONST_0) ;
mv.visitInsn(Opcodes.IRETURN) ;
mv.visitLabel(after ) ;
mv.visitInsn(Opcodes.RETURN) ;
mv.visitTryCatchBlock(tryStart , tryEnd , handler , "java/lang/ArithmeticException" ) ;
mv.visitMaxs(2, 4) ;
mv.visitEnd() ;
cw.visitEnd() ;
}}
Multiple exception handlers with catch-all:
Label tryStart = new Label(); Label tryEnd = new Label(); Label npeHandler = new Label(); Label aioobHandler = new Label(); Label defaultHandler = new Label();
mv.visitLabel(tryStart); // ... protected code ... mv.visitLabel(tryEnd);
mv.visitLabel(npeHandler); mv.visitVarInsn(Opcodes.ASTORE, 1); mv.visitInsn(Opcodes.ICONST_0); mv.visitInsn(Opcodes.IRETURN);
mv.visitLabel(aioobHandler); mv.visitVarInsn(Opcodes.ASTORE, 1); mv.visitInsn(Opcodes.ICONST_M1); mv.visitInsn(Opcodes.IRETURN);
mv.visitLabel(defaultHandler); mv.visitVarInsn(Opcodes.ASTORE, 1); mv.visitInsn(Opcodes.ICONST_0); mv.visitInsn(Opcodes.IRETURN);
mv.visitTryCatchBlock(tryStart, tryEnd, npeHandler, "java/lang/NullPointerException"); mv.visitTryCatchBlock(tryStart, tryEnd, aioobHandler, "java/lang/ArrayIndexOutOfBoundsException"); mv.visitTryCatchBlock(tryStart, tryEnd, defaultHandler, null);
Key points:
visitTryCatchBlock(start, end, handler, type) registers the handler
type is the internal name of the exception class, or null for catch-all
Exception handlers receive the exception on the stack (store it with ASTORE)
Try-catch blocks can overlap and nest
The JVM tries handlers in order; put specific exceptions before catch-all
visitTryCatchBlock can appear anywhere in the method, but start/end/handler labels must be defined