WithCleanup[expr,cleanup]
evaluates expr, running cleanup before returning the result, even if an abort, throw, etc. was generated during the evaluation of expr.
WithCleanup[init,expr,cleanup]
evaluates init before evaluating expr, blocking aborts, throws, etc. in both init and cleanup.
WithCleanup
WithCleanup[expr,cleanup]
evaluates expr, running cleanup before returning the result, even if an abort, throw, etc. was generated during the evaluation of expr.
WithCleanup[init,expr,cleanup]
evaluates init before evaluating expr, blocking aborts, throws, etc. in both init and cleanup.
Details
- The following types of operations are blocked in various ways in init and cleanup in WithCleanup:
-
aborts Abort and interactive aborts constraints termination based on TimeConstrained, MemoryConstrained control transfers Throw, Confirm, Goto, Break, Continue, … - If an abort is initiated during the evaluation of init, it is not immediately acted upon, and expr is not evaluated, but cleanup is.
- If an abort is initiated during the evaluation of expr, that evaluation is aborted, but cleanup is still executed.
- If an abort is initiated during the evaluation of cleanup, the abort is postponed until the evaluation of cleanup is complete.
- Constraints generated externally through constructions such as TimeConstrained[... WithCleanup[...]... ] behave in WithCleanup like aborts.
- If a control transfer whose destination is outside WithCleanup[...] occurs within init or expr, the evaluation of init or expr is terminated, cleanup is evaluated, and then the transfer occurs.
- If a control transfer occurs during the evaluation of cleanup, it is not postponed.
Examples
open all close allBasic Examples (2)
Clean up the assignment to x before returning the result:
WithCleanup[x = 7;x ^ 2, Clear[x]]The cleanup is done even if there is an abort in the main expression being evaluated:
WithCleanup[Echo[1], Abort[];Echo[2], Echo[3]]The same happens with other types of exceptions:
Catch[WithCleanup[Echo[1], Throw[x];Echo[2], Echo[3]]]Scope (2)
The cleanup is executed even though the evaluation is aborted:
f[WithCleanup[Abort[], Echo[1]]]f[WithCleanup[Echo[1];Abort[];Echo[2], Echo[3], Echo[4]]]The cleanup is done if an external constraint is reached during the evaluation of the main expression:
TimeConstrained[WithCleanup[Echo[1], Pause[5];Echo[2], Echo[3]], 1]MemoryConstrained[WithCleanup[Echo[1], Expand[(x + y)^10];Echo[2], Echo[3]], 1000]Constraints internal to WithCleanup are not treated specially:
WithCleanup[Echo[1], TimeConstrained[Pause[5], 1];Echo[2], Echo[3]]Applications (1)
Ensure that work files are properly closed even if a computation is interrupted:
TimeConstrained[WithCleanup[file = CreateFile[], Do[Pause[.9];Write[file, i], {i, Infinity}], Close[file]], 3]The data was safely written to disk:
FilePrint[file]Similarly, ensure that temporary files are deleted no matter how a computation ends:
TimeConstrained[WithCleanup[Do[Pause[.9];Write[file, i], {i, Infinity}], Close[file];DeleteFile[file]], 3]The file was successfully deleted:
FileExistsQ[file]Properties & Relations (3)
An abort generated during initialization or cleanup will not prevent them from evaluating completely:
WithCleanup[Abort[];Print[init], Print[main], Print[cleanup]]WithCleanup[Print[init], Print[main], Abort[];Print[cleanup]]An abort during the evaluation of the main expression will cause its evaluation to end immediately:
WithCleanup[Print[init], Abort[];Print[main], Print[cleanup]]An external control transfer in any argument will immediately end that argument's evaluation:
WithCleanup[Print["before throw"];Throw[end];Print["after throw"], Print[main], Print[cleanup]]//CatchNote that the evaluation of the cleanup will happen if the transfer starts in an earlier argument:
WithCleanup[Print[init], Print["before throw"];Throw[end];Print["after throw"], Print[cleanup]]//CatchIn the last argument, the control transfer takes effect immediately:
WithCleanup[Print[init], Print[main], Print["before throw"];Throw[end];Print["after throw"]]//CatchThe initialization and cleanup are effectively wrapped in AbortProtect:
Print[1];AbortProtect[Abort[];Print[2]]WithCleanup[Print[1], Abort[];Print[2]]Possible Issues (1)
Computations in the initialization and cleanup cannot be interactively aborted or time-constrained:
TimeConstrained[WithCleanup[Print["main"], Pause[5];Print["essential"]], 1]//AbsoluteTimingMove all nonessential code into the main expression:
TimeConstrained[WithCleanup[Print["main"];Pause[5], Print["essential"]], 1]//AbsoluteTimingSee Also
AbortProtect CompoundExpression Block Once Close DeleteFile
Function Repository: BlockProtected
Related Guides
History
Text
Wolfram Research (2020), WithCleanup, Wolfram Language function, https://reference.wolfram.com/language/ref/WithCleanup.html.
CMS
Wolfram Language. 2020. "WithCleanup." Wolfram Language & System Documentation Center. Wolfram Research. https://reference.wolfram.com/language/ref/WithCleanup.html.
APA
Wolfram Language. (2020). WithCleanup. Wolfram Language & System Documentation Center. Retrieved from 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: 12-June-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: 12-June-2026]}