Python is an extensively used language when it comes to various applications including web development, machine learning, data analysis and automation etc. The powerful library support in Python allows developers to build robust applications with minimal hassle. However, even with Python, we can face trouble and one such trouble is raised as an exception in specific cases, in the form of an OSError. In this guide, we’ll cover what exactly an OSError is and how can we handle it in Python programming.
What is an OSError?
So, what is OSError in Python? OSError is an exception raised by the Python interpreter that is related to the operating system and limited to the execution of the program. In simpler words, the operating system where your program is running encounters an error and hence raises an exception in the form of an OSError exception. Some common reasons for this include invalid arguments provided by user while executing certain commands, running out of disk space, attempting to write in read-only directories and various other similar causes.
Let’s get into the details of how we can handle an OSError in Python.
Python OSError – Handling
In order to handle the OSError exception, we can use the try-except block in our Python code.
We can also use the else block to execute the code in case of successful completion of the try block.
Syntax
try: #code causing OSError except OSError as e: #handle the exception else: #execute if try block is executed completely without any exception
Example 1: OSError handling using try-except-else
f = open('file.txt', 'r') try: print(f.read()) except OSError: print('Error occured while reading file') else: print('File read successfully')
Output:
Error occured while reading file
Example 2: OSError handling in Python script
import os try: os.mkdir('MyFolder') except OSError: print('Error creating directory') else: print('Directory successfully created')
Output:
Directory successfully created
Example 3: OSError handling in Python with multiple exceptions
import os import sys try: os.mkdir('MyFolder') f = open('file.txt', 'r') except OSError as e: print('OSError occurred: ', e.strerror) except: print('Unknown Exception:', sys.exc_info()[0]) else: print('Operation successful') f.close()
Output:
OSError occurred: [Errno 17] File exists: 'MyFolder'
Conclusion:
In the above guide, we explored the concept of OSError in Python and learnt handling this exception using Python try, except, and else block. We saw several examples, demonstrating in detail how to solve or handle a problem when it arises in the form of an OSError exception.