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 :
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:

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.
Go to:
PREV : Simulated Database Connection Exception.
NEXT : Specific Exception Handling Actions.
PHP Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.