cftry中的Coldfusion变量不持久

Bet*_*ock 4 coldfusion try-catch cfml

<cftry<cfmail标签外面。在<cftrya 内设置变量x。变量x无法通过生存</cftry>

<cfoutput>
<cftry>
<cfmail

          from     = "user@example.org"  
          to       = "other@example.org"          
          password = "something"
          username = "user@example.org"     
          server   = "localhost"                            
          replyto  = "user@example.org"
          subject  = "try-catch"               
          type     = "html"   >   

  <cfset x = 'abc'>

  this is to test email
  </cfmail>
  success

  <cfcatch>
  <cfoutput> email failed </cfoutput>
  </cfcatch
</cftry>


<!--- there is no variable x --->
x is #x#
</cfoutput>
Run Code Online (Sandbox Code Playgroud)

我想找到某种方法来在结束后提取x的值<cftry。我尝试过在内部使用不同的范围进行设置<cftry

<cfset register.x = 'abc'>  or even
<cfset session.x = 'abc'>
Run Code Online (Sandbox Code Playgroud)

但是这些都没有将x保留在之外<cftry>。有人可以建议一种将x保留到之外的方法</cftry>吗?

Ale*_*lex 11

看起来您对异常处理有误解。try仅在没有例外的情况下,内部代码才完全执行。一旦内部发生异常try,执行就会停止并跳转到catch

例子1

<cftry>

    <cfset x = "everything is ok">

    <cfcatch>
        <cfset x = "an exception occured">
    </cfcatch>
</cftry>

<cfoutput>#x#</cfoutput>
Run Code Online (Sandbox Code Playgroud)

这将始终输出everything is ok,因为try可以执行其中的代码而不会引起异常。

例子2

<cftry>

    <cfthrow message="I fail you!">

    <cfset x = "everything is ok">

    <cfcatch>
        <cfset x = "an exception occured">
    </cfcatch>
</cftry>

<cfoutput>#x#</cfoutput>
Run Code Online (Sandbox Code Playgroud)

这将始终输出an exception occured,因为其中的代码try仅执行到抛出异常的地步(我们在此处故意使用来执行此操作<cfthrow>)。

例子3

<cftry>

    <cfset x = "everything is ok">

    <cfthrow message="I fail you!">

    <cfcatch>
        <cfset x = "an exception occured">
    </cfcatch>
</cftry>

<cfoutput>#x#</cfoutput>
Run Code Online (Sandbox Code Playgroud)

这仍然会输出an exception occured。尽管该<cfset x = "everything is ok">语句已正确执行并设置了变量x,但catch由于抛出异常,我们仍跳到了该位置。

示例4(这是您的问题!)

<cftry>

    <cfthrow message="I fail you!">

    <cfset x = "everything is ok">

    <cfcatch>
        <!--- we are doing nothing --->
    </cfcatch>
</cftry>

<cfoutput>#x#</cfoutput>
Run Code Online (Sandbox Code Playgroud)

这将引发运行时错误,提示您x未定义。为什么?因为x由于遇到异常,所以从未达到声明的声明。而且catch也没有引入变量。

长话短说

<cfmail>正在引起异常,<cfset x = 'abc'>并且从未达到。

修复

正确的错误处理意味着有意义地处理捕获的异常。不要走开<cfoutput> email failed </cfoutput>它,不要表现出您不在乎的行为。记录异常(<cflog>针对该异常)并对其进行监视。出于调试目的,您可以使用<cfrethrow>内部<cfcatch>保留原始异常,而不是静默吸收错误的真正原因。