Python @ DjangoSpin

Python: Handling exceptions - the try-except constructs

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Handling exceptions in Python

Handling exceptions in Python

There are instances when your code doesn't go as planned. Python provides the try-except constructs to handle such situations. If a statement in the try clause raises an error, code in the except construct is executed. Consider a situation where you are trying to open a file which does not exist. You want the user to see an elegant message telling what went wrong rather than a horrible cryptic traceback. Remember, users hate traceback.

>>> fh = open("fileOne.py")
Traceback (most recent call last):
    fh = open("fileOne.py")
FileNotFoundError: [Errno 2] No such file or directory: 'fileOne.py'


>>> try:
    fh = open("fileOne.py")
except FileNotFoundError:                   	# hit backspace to go back a tabspace
    print("Please specify a valid file.")
     
Please specify a valid file.

To know more about Exception Handling, view this and this.


See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply