0

We have the below Javaassist Code to add printStackTrace() to a catch block present inside a 3rd party Class

int position = catchBlocks[i].block().position();
int lineNumber = ctMethod.getMethodInfo().getLineNumber(position);
ctMethod.insertAt(lineNumber + 1, "System.out.println(\"Catch Block\");");
ctMethod.insertAt(lineNumber + 2, "e.printStackTrace();");

But, when we run - it throws the below error javaassist.CannotCompileException: [source error] no such class: e

What is that we are missing here?

Thanks in Advance!

Sabari
  • 127
  • 1
  • 13
  • 1
    What is the content of the try-catch-block? Can you access `e` in the `System.out.println()`? – dan1st Feb 28 '21 at 15:15
  • There is a ```for``` loop that processes a collection of entities inside a ```try-catch``` block. Any exception during processing an entity is not thrown immediately instead it waits until all entities are processed. If any of the entity is processed successfully the method returns successfully. If all of the entities fail, it throws a generic exception that is not so helpful. So we would like to call the printStackTrace() on all exceptions that are caught. When we add 'e' to the ```System.out.println()``` it fails with ```javaassist.CannotCompileException: [source error] no such field: e``` – Sabari Feb 28 '21 at 15:40
  • My Bad - the exception variable is ```exp``` not ```e```. If we use the variable inside ```System.out.println()``` it works but it's not working when we add the ```exp.printStackTrace()``` statement. Thank you! – Sabari Feb 28 '21 at 16:50

0 Answers0