So, I have been reading about the exceptions today on the PHP online manual, and realize I have yet to understand the purpose or real necessity of the finally keyword. I have read some posts here, so my question is slightly different.
I understand that we can use finally in this way:
function hi(){
return 'Hi';
}
try {
throw new LogicException("Throw logic \n");
} catch (InvalidArgumentException $e) {
echo $e->getMessage();
}
echo hi();
output:
Fatal error: Uncaught LogicException: Throw Logic in C:\Users\...a.php:167
Stack trace:
#0 {main}
thrown in C:\Users\...a.php on line 167
So, in this case the function hi(); is not being execute and for a good reason. I understand if exception is not handled php interpreter halts the script. good. So far from what I read, finally enables us to execute the function hi(); even if the exception is not handled (even though I don't know why)
So, this one I understand.
try {
throw new LogicException("Throw logic \n");
} catch (InvalidArgumentException $e) {
echo $e->getMessage();
}finally{
echo hi();
}
output:
Hi
Fatal error: Uncaught LogicException: Throw Logic in C:\Users\...a.php:167
Stack trace:
#0 {main}
thrown in C:\Users\...a.php on line 167
This on should the exception error as well as the 'hi' message from the function, even those I don't know any usage for this. But what I don't undersand this, even if we catch the LogicException
with catch (LogicException $e)
and no exceptions were thrown still we would see the function being execute, and we would see the 'hi' message. as in this example
try {
throw new LogicException("Throw logic \n");
} catch (LogicException $e) {
echo $e->getMessage();
}finally{
echo hi();
}
outputs
// Throw logic
// Hi
So, we still see the function hi()
executed even though we have no Uncaught exceptions. Why and what is the use for this?
I thought the finally block was to be used as a last resort in case the exceptions were not caught, even if that wasn't the case then why is it the use to run it?