ColdFusion: Small Try/Catch Gotcha With CreateObject() and Exceptions
Exceptions can be deceptive and loathsome creatures at times. Case in point, I was happily using createObject() to load an object from a java jar in my classpath. I then added a try/catch. So I could detect when the jar probably was not added to the CF classpath properly, and display a more meaningful error message.
<cfscript>
try
{
handler = createObject("java", "net.sourceforge.barbecue.BarcodeImageHandler");
}
catch(java.lang.ClassNotFoundException e)
{
throwError(message="Verify the Barbecue jar is in your CF classpath", type="SupportingClassNotFound");
}
</cfscript>
Great in theory, the only problem was my try/catch did not work. I double checked the stack trace and it sure seemed like I was catching the correct exception type: java.lang.ClassNotFoundException. So I tried the broader type java.lang.Exception. Then cfdump'd the details, to see if I could spot the problem. Sure enough, the actual exception type was not what CF was reporting on the error screen. The actual exception type being:coldfusion.runtime.java.JavaObjectClassNotFoundException.
(Boy, what a mouthful. As if the base exception name is not long enough already...?)
Apparently the stack trace in the error page was displaying the RootCause, not the actual exception thrown. While that makes some sense, unfortunately the thrown exception type is what is needed to catch the darned thing. Anyway, once I changed my try/catch to use the actual exception type being thrown, everything was just dandy.<cfscript>
What is the world coming to when you cannot even trust error messages Oh, wait. Scratch that. Error messages lie all the time. I am sure they do not mean to lie, they just hold back critical information when you most need it. The secretive little trolls ;)
try
{
handler = createObject("java", "net.sourceforge.barbecue.BarcodeImageHandler");
}
catch(coldfusion.runtime.java.JavaObjectClassNotFoundException e)
{
throwError(message="Verify the Barbecue jar is in your CF classpath", type="SupportingClassNotFound");
}
</cfscript>
0 comments:
Post a Comment