finally
executes every*† time
Regardless of errors, exceptions, or even return
statements, the finally
block of code will run.
*It will not run if the try
or catch
blocks execute die
/exit
.
Exception
One common use I see is closing a database connection in a long running worker - you want this to happen every time [with or without an exception] so you don't end up with a dangling connection that blocks the database server from accepting new connections.
Consider this pseudo-code:
try {
$database->execute[$sql];
} finally {
$database->close[];
}
Here we will always close the database connection. If it's a normal query, we close connection after success, and the script will continue to execute.
If it's an erroneous query, then we still close after the exception has been thrown, and the uncaught exception will cause the script to halt.
Here's
an example with catch
doing some logging.
try {
$database->execute[$sql];
} catch [Exception $exception] {
$logger->error[$exception->getMessage[], ['sql' => $sql]];
throw $exception;
} finally {
$database->close[];
}
This will make it close the connection with or without an exception.
Return
One of the more obscure behaviors is its ability to execute code after a return statement.
Here you can set a variable after the function has returned:
function foo[&$x]
{
try {
$x = 'trying';
return $x;
} finally {
$x = 'finally';
}
}
$bar = 'main';
echo foo[$bar] . $bar;
tryingfinally
but an assignment will be what's returned in try:
$bar = foo[$bar];
echo $bar . $bar;
tryingtrying
and returning in the finally overrides the return in the try:
function baz[]
{
try {
return 'trying';
} finally {
return 'finally';
}
}
echo baz[];
finally
note this behavior was different in php 5:
finallyfinally
finallyfinally
finally
//3v4l.org/biO4e
Exceptional Return
You can kinda make it look like throwing 2 exceptions to bubble up at the same time:
try {
throw new Exception['try'];
} finally {
throw new Exception['finally'];
}
Fatal error: Uncaught Exception: try in /in/2AYmF:4 Stack trace: #0 {main} Next Exception: finally in /in/2AYmF:6 Stack trace: #0 {main} thrown in /in/2AYmF on line 6 Process exited with code 255.
//3v4l.org/2AYmF
But you can't really catch the "first" exception that I'm aware of to do anything fun at runtime:
try {
try {
throw new Exception['try'];
} finally {
throw new Exception['finally'];
}
} catch [Exception $exception] {
echo 'caught ' . $exception->getMessage[];
}
caught finally
//3v4l.org/Jknpm
* Die
If you exit
or die
then the
finally
block will not execute.
try {
echo "trying";
die;
} finally {
echo "finally";
}
echo "end";
trying
//3v4l.org/pc9oc
† Hardware Failure
Finally, you should understand that the finally
block will not execute if someone pulls the power plug on your server 😉 and although I haven't tested it, I'd expect memory exhaustion to skip it too.
Introduction
There is a peculiar behaviour of finally block when either try block or catch block [or both] contain a return statement. Normally return statement causes control of program go back to calling position. However, in case of a function with try /catch block with return, statements in finally block are executed first before returning.
Example
In following example,div[] function has a try - catch - finally construct. The try block without exception returns result of division. In case of exception, catch block returns error message. However, in either case statement in finally block is executed first.
Example
Live Demo
Output
Following output is displayed
This block is always executed Division by 0
Change value of $y to 5. Following output is displayed
This block is always executed 2
Updated on 18-Sep-2020 08:47:10
- Related Questions & Answers
- Differentiate between Interface design and Interaction design
- PHP Exception Handling with finally
- Difference Between Final, Finally and Finalize in Java
- What is the difference between final, finally and finalize[] in Java?
- PHP return Statement
- final, finally and finalize in C#
- final, finally and finalize in Java
- Difference between Python and PHP.
- Difference between JavaScript and Php
- Difference Between PHP and JavaScript
- Difference Between PHP and Python
- Can we write any statements between try, catch and finally blocks in Java?
- PHP Return by Reference
- Return all dates between two dates in an array in PHP
- Difference between !== and ==! operator in PHP