Computer >> Computer tutorials >  >> Programming >> Python

How to handle an exception in Python?


The simplest way to handle exceptions in python is using the "try-except" block.

Example

try:
fob = open("test.txt", "r")
fob.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find the file or read data"
else:
print "Write operation is performed successfully on the file"
fob.close()

Output

Error: can't find the file or read data