Handling Java exceptions



You handle Java exceptions just as you handle standard ColdFusion exceptions, with the cftry and cfcatch tags. You specify the name of the exception class in the cfcatch tag that handles the exception. For example, if a Java object throws an exception named myException, you specify myException in the cfcatch tag.

Note: To catch any exception generated by a Java object, specify java.lang.Exception for the cfcatchtype attribute. To catch any Throwable errors, specify java.lang.Throwable in the cfcatch tag type attribute.

For more information on exception handling in ColdFusion, see Handling Errors.

Example: exception-throwing class

The following Java code defines the testException class that throws a sample exception. It also defines a myException class that extends the Java built-in Exception class and includes a method for getting an error message.

The myException class has the following code. It throws an exception with a message that is passed to it, or if no argument is passed, it throws a canned exception.

//class myException 
public class myException extends Exception  
{ 
    public myException(String msg) { 
        super(msg); 
    } 
    public myException() { 
        super("Error Message from myException"); 
    } 
}

The testException class contains one method, doException, which throws a myException error with an error message, as follows:

public class testException { 
    public testException ()  
    { 
    } 
    public void doException() throws myException { 
        throw new myException("Throwing an exception from testException class"); 
    } 
}

Example: CFML Java exception handling code

The following CFML code calls the testException class doException method. The cfcatch block handles the resulting exception.

<cfobject action=create type=java class=testException name=Obj> 
<cftry> 
    <cfset Obj.doException() > 
    <cfcatch type="myException"> 
        <cfoutput> 
            <br>The exception message is: #cfcatch.Message#<br> 
        </cfoutput>  
    </cfcatch> 
</cftry>