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:

<?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! :D

This entry was posted in Blog Post and tagged , . Bookmark the permalink.

One Response to Handling Exceptions in PHP and Python

  1. Pingback: Tweets that mention Handling Exceptions in PHP and Python | maSnun.com -- Topsy.com

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">