Die finally-Anweisung
Der Block finally wird zusammen mit den Konstrukten try und catch zur Ausnahmebehandlung verwendet. Der Code innerhalb von finally wird in jedem Fall ausgeführt - sowohl bei erfolgreicher Ausführung des try-Blocks als auch beim Auftreten einer Ausnahme.
Syntax
try {
// Code, der eine Exception verursachen könnte
} catch (Exception $e) {
// Behandlung der Exception
} finally {
// Code, der in jedem Fall ausgeführt wird
}
Beispiel
Beispiel mit erfolgreicher Codeausführung:
<?php
try {
$res = 10 / 2;
echo "Result: " . $res . "\n";
} catch (Exception $e) {
echo "Exception: " . $e->getMessage() . "\n";
} finally {
echo "This will always execute\n";
}
?>
Ausgabe des Codes:
Result: 5
This will always execute
Beispiel
Beispiel mit Ausnahmebehandlung:
<?php
try {
$res = 10 / 0;
echo "Result: " . $res . "\n";
} catch (Exception $e) {
echo "Exception: " . $e->getMessage() . "\n";
} finally {
echo "This will always execute\n";
}
?>
Ausgabe des Codes:
Exception: Division by zero
This will always execute
Beispiel
Verwendung von finally zur Ressourcenfreigabe:
<?php
$file = fopen("example.txt", "r");
try {
// Arbeit mit der Datei
if ($file) {
echo "File opened successfully\n";
}
} catch (Exception $e) {
echo "Exception: " . $e->getMessage() . "\n";
} finally {
if ($file) {
fclose($file);
echo "File closed in finally block\n";
}
}
?>
Ausgabe des Codes:
File opened successfully
File closed in finally block