Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to handle an exception in Python?

I have code that is raising an exception.

fob = open("test.txt", "r")
fob.write("This is my test file for exception handling!!")

How to handle this exception?


1 Answer
Manogna

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

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
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.