Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Handling OSError exception in Python

  • Last Updated : 19 Aug, 2020

Let us see how to handle OSError Exceptions in Python. OSError is a built-in exception in Python and serves as the error class for the os module, which is raised when an os specific system function returns a system-related error, including I/O failures such as “file not found” or “disk full”.

Below is an example of OSError:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course


# Importing os module
import os
# os.ttyname() method in Python is used to get the terminal 
# device associated with the specified file descriptor.
# and raises an exception if the specified file descriptor 
# is not associated with any terminal device.

Output :

OSError: [Errno 25] Inappropriate ioctl for device

We can handle an ODError exception using try…except statements.


# importing os module  
import os 
# create a pipe using os.pipe() method 
# it will return a pair of  
# file descriptors (r, w) usable for 
# reading and writing, respectively. 
r, w = os.pipe() 
# (using exception handling technique) 
# try to get the terminal device associated  
# with the file descriptor r or w 
except OSError as error : 
    print("File descriptor is not associated with any terminal device"

Output :
[Errno 25] Inappropriate ioctl for device
File descriptor is not associated with any terminal device

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!