Is there a way to make Java Exceptions more informative?
For example, take this code from the ClassCastException docs:
Object x = new Integer(0);
System.out.println((String)x);
Java will give me a ClassCastException with a message like “Can’t cast something of type Integer to String”. How can I make it say: “Can’t cast the Integer 0 to a String” instead?
And if I tried to cast a String “foo” to a Person, to make it say: “Can’t cast the String foo to a Person”? So with the value of the object I was trying to cast.
Can I somehow replace the standard ClassCastException by the more informative one, so I don’t have to introduce lots of try/catch-blocks? Subclassing is of course an option, but then I would have to introduce lots of try/catch-blocks.
The reason why I’m asking is actually because of another programming language which compiles to the JVM, Clojure.
In Clojure, beginners often make this mistake:
(def my-list ("foo" "bar"))
This results into an error message:
java.lang.String cannot be cast to clojure.lang.IFn
It would be very helpful for beginners to see something like:
java.lang.String "foo" cannot be cast to clojure.lang.IFn
so they would get the clue that they are trying to use a string a a function here.
It would be nice to be able to inject these new Exceptions, for a learning environment, without actually re-writing the Clojure Compiler. It could be solved at the REPL level by catching these types of exceptions though. Still I’m curious if this is possible with some nifty techniques.
This problem was discussed at the latest Clojure Conj and is generally accepted as something to work on in the compiler. There isn’t a lot you can do after the fact to improve the stack traces yet, but rest assured you are not the only one seeking to improve this.
There is a good chance that the compiler will make the parse tree available to the build tools to enable people to create tools that will be able to interpret stack traces and print more meaningful messages, though these things will take time.