The finally Command

The finally block is used together with try and catch constructs for exception handling. The code inside finally will execute in any case - both upon successful execution of the try block and when an exception occurs.

Syntax

phptry {
  // Code that may throw an exception
} catch (Exception $e) {
  // Exception handling
} finally {
  // Code that will always execute
}

Example

Example with successful code execution:

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";
}
?>

Code execution result:

phpResult: 5
This will always execute

Example

Example with exception handling:

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";
}
?>

Code execution result:

phpException: Division by zero
This will always execute

Example

Using finally to free resources:

php<?php
$file = fopen("example.txt", "r");
try {
  // Working with the file
  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";
  }
}
?>

Code execution result:

phpFile opened successfully
File closed in finally block

See Also

  • the try construct,
    which is used for exception handling
  • the Exception class,
    which is the base class for all exceptions