WithCleanup[expr,cleanup]
即使在 expr 计算期间生成了中止、抛出等命令,函数也会计算 expr,在返回结果之前运行 cleanup.
WithCleanup[init,expr,cleanup]
在计算 expr 之前计算 init,在 init 和 cleanup 中禁用中止、抛出等.
WithCleanup
WithCleanup[expr,cleanup]
即使在 expr 计算期间生成了中止、抛出等命令,函数也会计算 expr,在返回结果之前运行 cleanup.
WithCleanup[init,expr,cleanup]
在计算 expr 之前计算 init,在 init 和 cleanup 中禁用中止、抛出等.
更多信息
- 下列运算类型在 WithCleanup 的 init 和 cleanup 中以多种方式被禁用:
-
中止 Abort 和交互中止 限制 基于 TimeConstrained,MemoryConstrained 的终止 控制传递 Throw, Confirm, Goto, Break, Continue, … - 若在 init 的计算期间有一个中止被初始化,则这个中止不会立即执行,即 expr 不会被计算,但 cleanup 仍会被计算.
- 若在 expr 的计算期间有一个中止被初始化, 则计算被中止,但 cleanup 会被继续执行.
- 若在 cleanup 的计算期间有一个中止被初始化,则该终止会延迟到 cleanup 的计算完成之后进行.
- 通过构建在外部产生的限制,如 TimeConstrained[... WithCleanup[...]... ],在 WithCleanup 中的表现类似终止.
- 如果目标在 WithCleanup[...] 之外的控制传递在 init 或 expr 内发生,则 init 或 expr 的计算会被中止,且 cleanup 被计算,然后传递发生.
- 若在 cleanup 的计算期间发生控制传递,则其不会被延迟.
范例
打开所有单元 关闭所有单元基本范例 (2)
范围 (2)
f[WithCleanup[Abort[], Echo[1]]]f[WithCleanup[Echo[1];Abort[];Echo[2], Echo[3], Echo[4]]]TimeConstrained[WithCleanup[Echo[1], Pause[5];Echo[2], Echo[3]], 1]MemoryConstrained[WithCleanup[Echo[1], Expand[(x + y)^10];Echo[2], Echo[3]], 1000]在 WithCleanup 内部的限制不会被特殊对待:
WithCleanup[Echo[1], TimeConstrained[Pause[5], 1];Echo[2], Echo[3]]应用 (1)
TimeConstrained[WithCleanup[file = CreateFile[], Do[Pause[.9];Write[file, i], {i, Infinity}], Close[file]], 3]FilePrint[file]TimeConstrained[WithCleanup[Do[Pause[.9];Write[file, i], {i, Infinity}], Close[file];DeleteFile[file]], 3]FileExistsQ[file]属性和关系 (3)
WithCleanup[Abort[];Print[init], Print[main], Print[cleanup]]WithCleanup[Print[init], Print[main], Abort[];Print[cleanup]]WithCleanup[Print[init], Abort[];Print[main], Print[cleanup]]WithCleanup[Print["before throw"];Throw[end];Print["after throw"], Print[main], Print[cleanup]]//Catch注意,如果传递在更早前的参数就已经开始,则会发生清除命令的计算:
WithCleanup[Print[init], Print["before throw"];Throw[end];Print["after throw"], Print[cleanup]]//CatchWithCleanup[Print[init], Print[main], Print["before throw"];Throw[end];Print["after throw"]]//Catch初始化和清除都在 AbortProtect 中有效封装:
Print[1];AbortProtect[Abort[];Print[2]]WithCleanup[Print[1], Abort[];Print[2]]文本
Wolfram Research (2020),WithCleanup,Wolfram 语言函数,https://reference.wolfram.com/language/ref/WithCleanup.html.
CMS
Wolfram 语言. 2020. "WithCleanup." Wolfram 语言与系统参考资料中心. Wolfram Research. https://reference.wolfram.com/language/ref/WithCleanup.html.
APA
Wolfram 语言. (2020). WithCleanup. Wolfram 语言与系统参考资料中心. 追溯自 https://reference.wolfram.com/language/ref/WithCleanup.html 年
BibTeX
@misc{reference.wolfram_2026_withcleanup, author="Wolfram Research", title="{WithCleanup}", year="2020", howpublished="\url{https://reference.wolfram.com/language/ref/WithCleanup.html}", note=[Accessed: 04-July-2026]}
BibLaTeX
@online{reference.wolfram_2026_withcleanup, organization={Wolfram Research}, title={WithCleanup}, year={2020}, url={https://reference.wolfram.com/language/ref/WithCleanup.html}, note=[Accessed: 04-July-2026]}