How to handle an exception in Python?

PythonServer Side ProgrammingProgramming

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
raja
Published on 07-Dec-2017 11:10:39
Advertisements