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.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyYou 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 newExceptionwith 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
divideormultiply) - Second line: A number (example:
5or0or2.5)
Expected output:
- If the operation succeeds:
Result:followed by the calculated value, thenOperation completedon a new line - If division by zero occurs:
Error: Cannot divide by zero, thenOperation completedon 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
tryblock 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
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Functions
Anonymous FunctionsClosures and 'use'Arrow FunctionsCallback FunctionsUsing 'call_user_func'Variable FunctionsPassing by ReferenceRecursive FunctionsRecap: Function Medley4Multi-dimensional Arrays
Creating a 2D ArrayAccessing 2D Array ElementsModifying 2D Array ElementsIterating with Nested Loops2D Associative ArraysRecap: Simple Grid Exercise2Advanced Array Manipulations
Adding with 'array_push'Removing with 'array_pop'Adding with 'array_unshift'Removing with 'array_shift'Merging Indexed ArraysMerging Associative ArraysExtracting with 'array_slice'Values with 'in_array'Keys with 'array_search'Recap: Playlist Exercise5Student Gradebook
Project Setup: Data StructureAdding a New StudentAdding a Grade to a StudentCalculating Student's AverageFinding the Top StudentGenerating a Report Card8Error and Exception Handling
Understanding PHP ErrorsThe 'try...catch' BlockThe 'finally' BlockThrowing an ExceptionCreating a Custom ExceptionUsing a Custom ExceptionRecap: Input Validation3Sorting Arrays
Sort Indexed Arrays AscendingSort Indexed Arrays DescendingSort Assoc Arrays by ValueSort Assoc Arrays by KeyNatural Order SortingCustom Sorting with 'usort'Recap: Leaderboard Sorting