Thursday, September 4, 2025
HomeLanguagesHandling OSError exception in Python

Handling OSError exception in Python

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: 

Python




# 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.
print(os.ttyname(1))


Output : 

OSError: [Errno 25] Inappropriate ioctl for device

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

Python




# 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
try :
    print(os.ttyname(r)) 
     
except OSError as error :
    print(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
RELATED ARTICLES

Most Popular

Dominic
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS