I have code that attempts to redefine a class at runtime using a ClassFileTransformer
and an instance of Instrumentation
.
However, I’ve noticed that the transform
method of ClassFileTransformer
fails to throw any exceptions.
Here’s an example (tested in java 8 and 17):
import net.bytebuddy.agent.ByteBuddyAgent;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
public class Main {
public static void main(String[] args) {
// implementation 'net.bytebuddy:byte-buddy-agent:1.14.13'
ByteBuddyAgent.install();
Instrumentation instrumentation = ByteBuddyAgent.getInstrumentation();
instrumentation.addTransformer(new Transformer(), true);
try {
instrumentation.retransformClasses(Klass.class);
}catch (Exception e) {
System.out.println("An error occurred: " + e.getMessage());
return;
}
System.out.println("Finished successfully");
}
private static class Transformer implements ClassFileTransformer {
@Override
public byte[] transform(ClassLoader cl, String name, Class<?> klass, ProtectionDomain pd, byte[] classfileBuffer) {
System.out.println("Transforming class " + klass.getName());
throw new RuntimeException("Example exception");
}
}
private static class Klass {}
}
This code throws an exception and should logically trigger the “An error occurred: ” message.
Instead, no exception is caught by the catch block:
Transforming class Main$Klass
Finished successfully
Do you know what causes this behavior and whether it can be avoided?