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:
<?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:
#!/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!
Pingback: Tweets that mention Handling Exceptions in PHP and Python | maSnun.com -- Topsy.com