Categories
PHP Python

Handling Exceptions in PHP and Python

It’s really a very important programming practice to properly handle any possible exceptions… It makes the code more stable, efficient and re-usable.

PHP:
PHP now has a very good exception handling mechanism. Just put a “try” block and then “catch ” the exception if anything goes wrong 🙂

Have a look at the following code:

The code is self explanatory. But you must use the “Exception” word before $e in the catch block to get things going perfectly. Like I did, you can “throw” a new exception in case there was really something unexpected in your code 🙂

Python:
Python is just a fantastic language. Here’s the Python equivalent of the above code snippet:

The only difference in PHP and Python’s exception handling is it’s language structure. In Python, we don’t throw an exception, rather we raise one. Just a bit of politeness! 😉

Conclusion:
Both PHP and Python has very good exception handling techniques. I can’t discuss them all on this blog but you should consult the respective manuals to master them. They are really very essential! 😀

One reply on “Handling Exceptions in PHP and Python”

Comments are closed.