๐ŸŽ“ A1Learner
๐Ÿ”
0 of 38 lessons completed

Finally in Depth

The finally block is a block that runs after a try block in every case. It suits steps that must always happen, like closing what a program opened.

Finally runs after a clean try

Nothing fails in this try block. The finally line prints after the try line.

<?php
try {
  echo "Try ran\n";
} finally {
  echo "Finally ran\n";
}

Finally runs on the success path and the failure path

The program runs two try blocks. The first succeeds, and the second throws an exception that its catch block handles.

<?php
try {
  echo "First try ran\n";
} finally {
  echo "First finally ran\n";
}
try {
  throw new Exception("Second try failed");
} catch (Exception $e) {
  echo $e->getMessage(), "\n";
} finally {
  echo "Second finally ran\n";
}

Finally runs before a return finishes

The function returns a value from inside its try block. The finally line prints first, and the returned value prints after it.

<?php
function give() {
  try {
    return "from try";
  } finally {
    echo "finally runs\n";
  }
}
echo give(), "\n";

Example

<?php
try {
  echo "File opened\n";
  echo "File read\n";
} finally {
  echo "File closed\n";
}
try {
  echo "File opened\n";
  throw new Exception("Read failed");
} catch (Exception $e) {
  echo $e->getMessage(), "\n";
} finally {
  echo "File closed\n";
}

Key points

  • A finally block sits after a try block, and after a catch block when there is one.
  • Finally runs when the try block finishes with no failure.
  • Finally runs after a catch block handles a failure.
  • Finally runs before a return inside try hands its value back.
  • A try block can pair with finally on its own, with no catch block.

In this example, the lines tell an open and close story with fixed text. The first run opens and reads, and the finally block closes it. The second run opens and then throws, the catch block prints Read failed, and the finally block still closes it. Both runs end with the same closing line.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A return statement sits inside a try block that has a finally block. When does the finally block run?