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
Updated on 13-Feb-2020 05:00:21

Advertisements