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

phptry {
  // 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<?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:

phpResult: 5
This will always execute

Beispiel

Beispiel mit Ausnahmebehandlung:

php<?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:

phpException: Division by zero
This will always execute

Beispiel

Verwendung von finally zur Ressourcenfreigabe:

php<?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:

phpFile opened successfully
File closed in finally block

Siehe auch

  • das Konstrukt try,
    das zur Ausnahmebehandlung verwendet wird
  • die Klasse Exception,
    die die Basisklasse für alle Exceptions ist