What is the finally block in try-catch in PHP?
Exception
An exception can be defined as a discontinuity in the normal flow of program execution. It includes errors that cause a complete disruption in the execution of code.
Exception handling
Exception handling allows the program to respond appropriately when an exception occurs. In the event of an exception, exception handling makes the program respond to its actual cause and its place of occurrence.
In this shot, we'll learn how to use the finally block in try-catch exception handling.
try-catch
The try-catch statement is used to check for errors in code. It guides the program to give specific error messages (in the catch block) when an error occurs in the try block.
finally
Code in the finally block will run irrespective of the block it is in. In try-catch, the finally block is used to execute a code block whether or not an error occurs. It can be used to continue the flow of the application even though an error occurs when the same code is placed in the catch block.
Note: Codes in the
finallyblock will be executed even though code in thetryblock has an error that thecatchblock needs to display.
Syntax
(try(//Protected code)catch Exception e1)(//Catch block)(finally//Cleanup code)
Example
Let's look at the code below:
<?phpfunction func($x) {if (!$x) {throw new Exception('Division by zero.');}}try {func('') . "\n";} catch (Exception $e) {echo 'Caught exception: ', $e->getMessage(), "\n";} finally {echo "First finally.\n";}?>
Explanation
In the code above:
- Line 4: We define an exception handling scenario under which the program will throw an exception if the number supplied to the
funcfunction is empty. - Line 9: We start our
tryblock. - Line 10: We call the
funcfunction and pass an empty string to it. This will throw an error. - Line 11: We use the
catchblock to catch and echo the error thrown. - Line 13: We use the
finallyblock to echo a message (First finally.\n).
Note: The
finallyblock can be used to execute any code we want, not just echo a string to the screen.