w3resource

PHP exception handling with the finally block


9. Finally Block in Exception Handling

Write a PHP script that implements the use of the finally block in exception handling.

Sample Solution:

PHP Code :

<?php
try {
    // Code that may throw an exception
    $number = 0;
    
    if ($number === 0) {
        throw new Exception("Number cannot be zero.");
    }
    
    $result = 200 / $number;
    echo "Result: " . $result;
} catch (Exception $e) {
    echo "An error occurred: " . $e->getMessage();
} finally {
    // Code that will always be executed
    echo "This will always be executed.";
}
?>

Sample Output:

An error occurred: Number cannot be zero.This will always be executed.

Explanation:

In the above exercise,

  • We have a try block that contains code that may throw an exception. We check if the $number is zero and throw an exception if it is.
  • The catch block catches the Exception and displays an appropriate error message using $e->getMessage().
  • The finally block is where you can include code that will always be executed, regardless of whether an exception was thrown or not. This example simply echos the message "This will always be executed."

Flowchart:

Flowchart: PHP exception handling with the finally block

For more Practice: Solve these Related Problems:

  • Write a PHP script that uses a try-catch-finally structure to execute cleanup code regardless of whether an exception was thrown.
  • Write a PHP function that demonstrates resource release in the finally block after an exception is caught.
  • Write a PHP program to simulate an operation that throws an exception, then use the finally block to output a termination message.
  • Write a PHP script to execute a series of tasks in a try block, catch a potential exception, and always run final code in the finally clause.

PHP Code Editor:



Contribute your code and comments through Disqus.

Previous: Exception handling.
Next: Handling specific exceptions.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.