I do a lot of coding in Python and one thing that I really love is the mindset of asking for forgiveness instead of permission. What’s this mean? It means that instead of sanity checking every little thing, just handling the exceptions that are thrown instead. In PHP this can be accomplished by using
A pretty primitive example but that’s the gist of it, instead of writing code with nested
if statements trying to control the flow, just wrap it all in a
try/catch and the control structure will immediately be halted when you encounter an
Exception (which you can
Unfortunately, PHP has it’s own error handling and
Exceptions are not always thrown (quite the shortcoming in my opinion) but you can always override the default error handler and have it throw exceptions instead, which is something I’ve discussed in the past.
If you’ve joined me in the revolution of running the most recent version of PHP (5.5+ as of this writing) then you have access to the
finally block as well.
finally is code that will always be executed regardless if an exception is thrown. Please keep in mind that this only works if there is another
try/catch block handling the code. That being said, this won’t work as you may expect:
Exception being thrown inside the
catch is not being caught, it raises a PHP fatal error. Now in this example, the
finally will be executed:
Keep in mind this is just for demonstration purposes, a real world example would be in situations where you have some nested logic (possibly spanning multiple files and/or classes) that is catching and throwing errors, but you still want to execute pieces of code regardless.
Asking for forgiveness instead of permission generally keeps your code flatter and closer to the left margin which helps readability and simplifies the control structure. Another lesson learned here is that coding in other languages can help expose you to concepts that can be applied in your language of choice, no reason to limit yourself.!