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 catch IOError Exception in Python?

If I run the following code, I am getting an error.

f = open(“foo.txt”, ‘r’)

How to catch this error and know its type?


1 Answer
Rajendra Dharmkar

IOError Exception

It is an error raised when an input/output operation fails, such as the print statement or the open() function when trying to open a file that does not exist. It is also raised for operating system-related errors.

If the given code is written in a try block, it raises an input/output exception, which is handled in the except block as shown given below

import sys
def whatever():
try:
f = open ( "foo.txt", 'r' )
except IOError, e:
print e
print sys.exc_type
whatever()

OUTPUT

[Errno 2] No such file or directory: 'foo.txt'
<type 'exceptions.IOError'>

Advertisements

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