views:

234

answers:

1

In ColdFusion 8 or below, is the marked line in the right place?

<cftry>
  <cfquery name="local.qry" datasource="myDatasource">
    SELECT ID FROM TableName
    WHERE ...
  </cfquery>
  <cfset local.result = local.qry.ID><!--- this line! --->
  <cfcatch>
    <cfset local.result = Variables.objDatabase.CatchError(cfcatch)>
  </cfcatch>
</cftry>

<cfreturn local.result>
+4  A: 

Yes. You could set it outside of the block, but why? At least this way, you'll catch any bizarre errors that might occur during assignment. It's not likely, but the query could succeed and the assignment could fail, so why not trap that potential issue?

You've already got the overhead of a try/catch, might as well add the assignment to the try block as well.

Shawn Grigson
@Shawn: If the assignment could fail, wouldn't every assignment you ever make have to be guarded with a try-catch block? When an assignment like this one can fail, you have such severe problems that a try-catch block will not help you.
Tomalak
It's extremely unlikely, that's for sure. And no, let's not go crazy doing a try/catch for every assignment. I'm just saying in this particular case you might as well apply the assignment there. And setting local.result in the <cfcatch> is the right idea, too, else the <cfreturn> will fail. In fact, you could just do, <cfreturn> in both places, rather than <cfset> and leave off the final <cfreturn>. Then you don't need to assign anything.
Shawn Grigson
Are you sure he could assign it outside of the block? I would think it would just raise another exception that local.qry.ID is undefined if the query fails.
Soldarnal