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

When the following code is run, I get an error.

f = open ( "JohnDoe.txt", 'r' )

How do I handle this exception and find its type?


1 Answer
Manogna

EnvironmentError is the base class for errors that come from outside of Python (the operating system, filesystem, etc.). EnvironmentError Exception is a subclass of the StandarError class. It is the base class for IOError and OSError exceptions. It is not actually raised unlike its subclass errors like IOError and OSError.

Any example of an IOError or OSError should be an example of Environment Error as well.

import sys
try:
f = open ( "JohnDoe.txt", 'r' )
except Exception as e:
print e
print sys.exc_type

OUTPUT

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

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