gpt4 book ai didi

cftry 中的冷聚变变量不存在

转载 作者:行者123 更新时间:2023-12-04 22:26:51 25 4
gpt4 key购买 nike

我在 <cftry 标签之外有一个 <cfmail。在 <cftry 中设置了一个变量 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>

我想找到某种方法来在 <cftry 结束后获取 x 的值。我尝试在 <cftry 中使用不同的范围设置它
<cfset register.x = 'abc'>  or even
<cfset session.x = 'abc'>

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

最佳答案

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

<cftry>

<cfset x = "everything is ok">

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

<cfoutput>#x#</cfoutput>
这将始终输出 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>
这将始终输出 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>
这仍然会输出 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>
这将抛出一个运行时错误,告诉您 x 未定义。为什么?因为由于遇到异常,永远不会到达声明 x 的语句。并且 catch 也不会引入变量。
长话短说
您的 <cfmail> 导致异常并且永远无法到达 <cfset x = 'abc'>
修复
正确的错误处理意味着有意义地处理捕获的异常。不要 <cfoutput> email failed </cfoutput> 你的方式摆脱它,表现出你不在乎。记录异常(有 <cflog> )并监视它。出于调试目的,您可以在 <cfrethrow> 中使用 <cfcatch> 来保留原始异常,而不是默默地吸收错误的真正原因。

关于cftry 中的冷聚变变量不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55523538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com