Reading Time: 1 minutesHandling 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): |
FileNotFoundError: [Errno 2 ] No such file or directory: 'fileOne.py' |
except FileNotFoundError: |
print ( "Please specify a valid file." ) |
Please specify a valid file . |
To know more about Exception Handling, view this and this.
See also: