> Is it best to wrap the try/catch around just the code that may
> be the problem, or to wrap the entire template? It seems to make
> more sense to me to wrap just the code that's likely to cause a
> problem (and the Adv. CF course material leads me to believe that
> too). However, I've seen some tutorials and even know someone who
> was in a class that told her to wrap the template.
>
> So what is the best practice?
The class steered her wrong. Here's my opinion on how to use exception
handling.
When you use an exception handler (CFTRY/CFCATCH), three things should be
true:
1. There is a clearly atomic, or limited, block of code which can be
isolated - a single algorithm, perhaps, or even less.
2. There is a relatively high likelihood that some specific known problem
may occur.
3. There is some appropriate response to that problem beyond a generic error
message.
If any of these isn't true, then you should use something other than an
CFTRY/CFCATCH exception handler. There are three other options for handling
problem conditions other than wrapping the problem code within an exception
handler. You can use CFERROR with TYPE="EXCEPTION", which will pass all
unhandled exceptions to a specific script that can execute any code, you can
use CFERROR with TYPE="REQUEST", which will pass unhandled errors to another
script that can't execute any code, or you can use the site-wide error
handler instead of the previous option.
If you wrap an entire script in a CFTRY block, you won't be able to respond
well to specific problems. For example, if you have three queries in a
script, and one of them fails, you won't be able to respond with the level
of granularity that you could if you had only one query in your CFTRY block.
Sure, you can write conditional logic within your CFCATCH blocks to try to
determine the problem after the fact, but this is a backwards approach.
Note that in (2) above, knowing that a specific problem may occur doesn't
mean you have to know why that problem may occur. For example, you may have
something that fails for reasons you don't understand. However, after
observing the failure once or twice, you'll know what the failure looks
like, and can write an appropriate exception handler.
Note also that in (3) above, knowing there's an appropriate response might
not necessarily mean knowing how the exception will be dealt with in the
end. For example, if you write a custom tag, your custom tag should throw an
exception back to the calling page if it runs into an insurmountable
problem. It is then the calling page's responsibility to handle the
exception.
Dave Watts, CTO, Fig Leaf Software
http://www.figleaf.com/
voice: (202) 797-5496
fax: (202) 797-5444
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Structure your ColdFusion code with Fusebox. Get the official book at
http://www.fusionauthority.com/bkinfo.cfm
Archives: http://www.mail-archive.com/cf-talk@houseoffusion.com/
Unsubscribe: http://www.houseoffusion.com/index.cfm?sidebar=lists