How to catch OSError Exception in Python?


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'>

Updated on: 27-Sep-2019

628 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements