Menu
Coddy logo textTech

The 'finally' Block

Part of the Logic & Flow section of Coddy's PHP journey — lesson 54 of 68.

Sometimes you need code that runs regardless of whether an exception occurs or not. The finally block provides this guarantee - it contains code that will always execute after a try...catch block completes, making it perfect for cleanup operations like closing files or database connections.

The finally block runs in all scenarios: when the try block succeeds without exceptions, when an exception is thrown and caught, and even when an exception is thrown but not caught. This reliability makes it invaluable for ensuring important cleanup code always runs.

<?php
try {
    echo "Attempting operation...\n";
    // Code that might throw an exception
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
} finally {
    echo "Cleanup completed.\n";
}
?>

The finally block executes after both the try and catch blocks have finished, providing a consistent place for essential cleanup code. This ensures your script properly handles resources and maintains a clean state, regardless of what happens during execution.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

You will receive two inputs: an operation type and a number. The first input is a string that will be either "divide" or "multiply". The second input is a number that will be used in the operation.

Read both inputs and create a try...catch...finally block. Inside the try block, check the operation type:

  • If the operation is "divide", check if the number is zero. If it is zero, throw a new Exception with the message "Cannot divide by zero". If the number is not zero, calculate 100 divided by the number and print "Result: " followed by the result.
  • If the operation is "multiply", calculate 100 multiplied by the number and print "Result: " followed by the result.

In the catch block, handle any exception by printing "Error: " followed by the exception message using the getMessage() method.

In the finally block, print "Operation completed".

Input format:

  • First line: An operation type string (either divide or multiply)
  • Second line: A number (example: 5 or 0 or 2.5)

Expected output:

  • If the operation succeeds: Result: followed by the calculated value, then Operation completed on a new line
  • If division by zero occurs: Error: Cannot divide by zero, then Operation completed on a new line

Cheat sheet

The finally block contains code that always executes after a try...catch block completes, regardless of whether an exception occurs. It's perfect for cleanup operations like closing files or database connections.

The finally block runs in all scenarios:

  • When the try block succeeds without exceptions
  • When an exception is thrown and caught
  • When an exception is thrown but not caught
<?php
try {
    echo "Attempting operation...\n";
    // Code that might throw an exception
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
} finally {
    echo "Cleanup completed.\n";
}
?>

The finally block executes after both the try and catch blocks have finished, ensuring essential cleanup code always runs.

Try it yourself

<?php
// Read inputs
$operation = trim(fgets(STDIN));
$number = floatval(fgets(STDIN));

// TODO: Write your code below
// Create a try...catch...finally block to handle the operation

?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow