Detail formatters to the Rescue!
#toString methods are a powerful debugging tool.
In the Eclipse debugger, the output of #toString is shown in the detail pane of the variables view. It is often useful to adapt the #toString method of your classes to display particular debugging information.
If you are debugging third-party code though, you cannot change their #toString method—bummer! The same applies to objects that belong to the Java API. Exception for example do not print their stack trace, which would be a most useful information when stepping through a catch block.
Detail formatters to the rescue!
Open preference and goto Java > Debug > Detail Formatters and add a new custom formatter for java.lang.Throwable with the following code snippet
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
this.printStackTrace(new java.io.PrintStream(baos));
return baos.toString();
Now, exceptions will print their stack trace!
public static void main(String[] args) {
try {
Arrays.asList().iterator().next();
}
catch (Exception ex) {
System.exit(-1); // Halt here
}
}
To verify, set a breakpoint in the catch above clause and view ex in the variable view…
Happy hacking!
NB: as you can see, there is some code that you are allowed to change and some code that you cannot touch—at least not unless magic tool support is provided. Not all programming languages are like this. There are more dynamic languages, as eg Ruby and Smalltalk, that allow you as a programmer to touch any code, both yours and other, and even to change any object at runtime. The reason static languages like Java do not allow this is because they want to enforce the Curry-Howard correspondence (a mathematical notion of security that cannot cope with dynamic changes) of the type system, but alas they do so at the cost of testability. I won’t say that Java is a Toyota … it is more like a Ford Model-T built when programmers did not yet care about testability.