Exceptions
Finally Cleanup
A finally block runs after try or catch, so cleanup can happen in one place.
Finally Cleanup
finally_cleanup.php
<?php
$mode = ;
$closed = "no";
try {
if ($mode !== "save") {
throw new Exception($mode);
}
$status = "saved";
} catch (Exception $error) {
$status = "recovered_" . $error->getMessage();
} finally {
$closed = "yes";
}
echo "mode=" . $mode . "\n";
echo "status=" . $status . "\n";
echo "closed=" . $closed . "\n";
<?php
$mode = ;
$closed = "no";
try {
if ($mode !== "save") {
throw new Exception($mode);
}
$status = "saved";
} catch (Exception $error) {
$status = "recovered_" . $error->getMessage();
} finally {
$closed = "yes";
}
echo "mode=" . $mode . "\n";
echo "status=" . $status . "\n";
echo "closed=" . $closed . "\n";
<?php
$mode = ;
$closed = "no";
try {
if ($mode !== "save") {
throw new Exception($mode);
}
$status = "saved";
} catch (Exception $error) {
$status = "recovered_" . $error->getMessage();
} finally {
$closed = "yes";
}
echo "mode=" . $mode . "\n";
echo "status=" . $status . "\n";
echo "closed=" . $closed . "\n";
always runs
Use finally for cleanup-like state that should happen after success or recovery.