Throwing And Catching Java Runtime Exceptions In ColdFusion
Last night, I started looking into Redis - an out-of-process Key-Value store. As part of the interaction with Jedis - the recommended Java client library for Redis - I need to handle specific Java runtime exceptions. I've never had to target Java runtime exceptions before, so I did a little reading of the ColdFusion documentation. It turns out that throwing and catching Java runtime exceptions is rather straightforward.
In the past, I've looked at throwing and catching custom errors in ColdFusion; but, those ColdFusion runtime exceptions are based on hierarchical type values. If we want to throw Java runtime exceptions, we need to create actual exception objects. And, when we want to catch specific Java runtime exceptions, we need to define a CFCatch block that targets the classname of the given Java exception object.
To see this in action, I've set up a Try/Catch block that throws and then catches a Java runtime exception:
<cfscript>
try {
// In order to throw a Java RuntimeException, we need to create an instance
// of our exception class.
exception = createObject( "java", "redis.clients.jedis.exceptions.JedisConnectionException" )
.init( javaCast( "string", "Something went wrong!" ) )
;
// When throwing a Java exception, you can only use the "object" parameter.
// This is mutually-exclusive with all other throw-parameters.
throw( object = exception );
// When you want to catch a specific Java exception, you can use the classname
// of the exception type in order to define a targeted CFCatch statement.
// --
// NOTE: The classname can be quoted or not.
} catch ( redis.clients.jedis.exceptions.JedisConnectionException error ) {
writeOutput( "Caught Java Runtime Exception: " & error.message );
}
</cfscript>
When you throw a Java runtime exception, you have to use the "object" parameter of the throw() method (or CFThrow tag). This parameter is mutually exclusive with all other CFThrow parameters.
When we run the above code, we get the following page output:
Caught Java Runtime Exception: Something went wrong!
I assume that most of the time, when you're dealing with Java runtime exceptions, you'll simply be catching errors, not throwing them. But, I needed to throw one in order to test the CFCatch block. Regardless, I love how easily ColdFusion allows us to integrate with the finer points of the underlying Java runtime.
Want to use code from this post? Check out the license.
Reader Comments
@All,
On a somewhat related note, apparently using JavaLoader interferes with the ability to target specific exceptions with the TYPE attribute of CFCatch:
http://www.compoundtheory.com/issue-with-cfcatch-and-javaloader/