So, I read about exceptions today in the online PHP manual and understand that I have yet to understand the purpose or real need of the finally keyword. I read a few posts here, so my question is slightly different.
I understand that we can finally use 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:
So, in this case, the function hi (); not executed for a good reason. I understand if the exception is not handled, the PHP interpreter stops the script. OK. So far, I'm reading, finally, allowing us to execute the hi () function; even if the exception is not handled (although I don't know why)
So, I understand that.
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:
In this case, there should be an exception error, as well as a “hi” message from this function, even those that I do not know for this. But I don’t understand this, even if we catch a LogicException
with catch (LogicException $e)
, and there were no exceptions, we would see what the function would look like and we would see a “hi” message. as in this example
try { throw new LogicException("Throw logic \n"); } catch (LogicException $e) { echo $e->getMessage(); }finally{ echo hi(); }
exits
So, we still see the hi()
function being executed, even if we have no Uncaught exceptions. Why and for what purpose? I thought the final block should have been used as a last resort in case exceptions were not caught, even if it wasn’t, then why use it?