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

When following code is run, I get error

import os
import sys
for i in range(5):
      print i, os.ttyname(i)

How do I handle this error and know it type?


1 Answer
Rajendra Dharmkar

OSError serves as the error class for the os module, and is raised when an error comes back from an os-specific function.

We can re-write the given code as follows to handle the exception and know its type.

#foobar.py
import os
import sys
try:
for i in range(5):
print i, os.ttyname(i)
except Exception as e:
print e
print sys.exc_type

If we run this script at linux terminal

$ python foobar.py

We get the following output

OUTPUT

0 /dev/pts/0
1 /dev/pts/0
2 /dev/pts/0
3 [Errno 9] Bad file descriptor
<type 'exceptions.OSError'>
Advertisements

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