Reading Time: 1 minutes
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.