Essentially it is to ensure that the flow of that block is always executed. Even if an exception occurs in the block started by try
, the finally
block will be executed before exiting the function and start dropping the function call stack.
In general it is used to terminate allocated resources, for example closing a file.
There may be a question of what the difference is to catch
which also runs when there is an exception. The difference is that catch
is only executed when there is the exception. finally
is executed with or without exception. The program execution flow goes from try
to finally
always, either because try
quit normally, or because it raised an exception. catch
is a conditional execution block (by throwing an exception), finally
is required execution.
Remembering that throwing an exception will enforce both the catch
and finally
blocks, but any code that comes after this try-catch-finally
block will not run .
You may get an impression of little use of it because of examples that do nothing useful effectively.
Documentation .
Good generic example:
$recurso = abrir_recurso();
try {
$resultado = use_rercurso($rercurso);
} finally {
libere_rercurso($rercurso); //acontecendo ou não uma exceção, o recurso será fechado
}
return $resultado;
Actual example taken blog :
function addRecord($record, $db) {
try {
$db->lock($record->table);
$db->prepare($record->sql);
$db->exec($record->params);
} catch(Exception $e) {
$db->rollback($record);
if (!write_log($e->getMessage(), $e->getTraceAsString())) {
throw new Exception('Unable to write to error log.');
}
} finally {
$db->unlock($record->table);
}
return true;
}
The example is bad because it captures Exception
and launches again but the general idea is this.
Suggested reading . It's not the same language but it works the same way.