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:
1 2 3 4 5 6 7 8 9 |
<?php function masnun() { throw new Exception("Damn!"); } try { masnun(); } catch (Exception $e) { echo "Exception: ".$e->getMessage()."\n"; } ?> |
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:
1 2 3 4 5 6 7 8 9 10 |
#!/usr/bin/env python def masnun(): raise Exception("Damn!") try: masnun() except Exception as e: print "Exception:", e |
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! 😀