# Exception handling example

The following example shows CFTRY and CFCATCH, using a sample data source called company and a sample included file, `includeme.cfm`.

If an exception occurs during the CFQUERY statement's execution, the application page flow switches to the CFCATCH TYPE="Database" exception handler. It then resumes with the next statement after the CFTRY block, once the CFCATCH TYPE="Database" handler completes.

Similarly, the CFCATCH TYPE="MissingInclude" block handles exceptions raised by the CFINCLUDE tag. Any unknown, but possibly recoverable, exceptions are handled by the CFCATCH TYPE="Any" block.

    <!--- Wrap code you want to check in a CFTRY block --->

    <CFTRY>
        <CFQUERY NAME="test" DATASOURCE="company">
            SELECT DepartmentID, FirstName, LastName
            FROM employees
            WHERE employeeID=#EmpID#
        </CFQUERY>

        <HTML>
        <HEAD>
            <TITLE>Test CFTRY/CFCATCH</TITLE>
        </HEAD>

        <BODY>
        <HR>
        <CFINCLUDE TEMPLATE="includeme.cfm">
        <CFOUTPUT QUERY="test">
        <P>Department: #DepartmentID#
        <P>Last Name: #LastName#
        <P>First Name: #FirstName#
        </CFOUTPUT>

        <HR>

    <!--- Use CFCATCH to test for missing included files. --->
    <!---     Print Message and Detail error messages. --->
    <!--- Block executes only if a MissingInclude exception is thrown. --->

        <CFCATCH TYPE="MissingInclude">
            <H1>Missing Include File</H1>
            <CFOUTPUT>
            <UL>
            <LI><B>Message:</B> #CFCATCH.Message#
            <LI><B>Detail:</B> #CFCATCH.Detail#
            <LI><B>File name:</B> #CFCATCH.MissingFilename#
            </UL>
            </CFOUTPUT>
        </CFCATCH>

    <!--- Use CFCATCH to test for database errors.--->
    <!---     Print error messages. --->
    <!--- Block executes only if a Database exception is thrown. --->

        <CFCATCH TYPE="Database">
        <H1>Database Error</H1>
        <CFOUTPUT>
        <UL>
        <LI><B>Message:</B> #CFCATCH.Message#
        <LI><B>Native error code:</B> #CFCATCH.NativeErrorCode#
        <LI><B>SQLState:</B> #CFCATCH.SQLState#
        <LI><B>Detail:</B> #CFCATCH.Detail#
        </UL>
        </CFOUTPUT>
        </CFCATCH>

    <!--- Use CFCATCH with TYPE="Any" --->
    <!--- to find unexpected exceptions. --->

        <CFCATCH TYPE="Any">
        <H1>Other Error: #CFCATCH.Type#</H1>

        <CFOUTPUT>
        <UL>
        <LI><B>Message:</B> #CFCATCH.message#
        <LI><B>Detail:</B> #CFCATCH.Detail#
        </UL>
        </CFOUTPUT>
        </CFCATCH>
    </CFTRY>

        </BODY>
        </HTML>