Catch OSError Exception in Python



The OSError in Python is commonly encountered when a system-related error occurs, such as a file not found, permission denied, or disk I/O errors. It is one of the built-in exceptions that helps in handling operating system-level failures.

In this article, you will learn how to catch and handle OSError using try-except blocks with examples.

When Does OSError Occur?

OSError may occur in the following situations -

  • Trying to open a non-existent file.
  • Permission denied while accessing a file or directory.
  • Invalid file path or I/O operation failures.

Example: File Not Found

In the following example, we try to open a file that does not exist. This raises an OSError (or specifically a subclass like FileNotFoundError), which we catch and handle -

try:
   with open("non_existing_file.txt", "r") as f:
      content = f.read()
except OSError as e:
   print("Caught OSError:", e)

Following is the output obtained -

Caught OSError: [Errno 2] No such file or directory: 'non_existing_file.txt'

In this example, since the file does not exist, OSError is raised and handled using a try-except block.

Example: Permission Denied

The following example shows an attempt to open a file without the proper permissions, which also raises OSError -

try:
   with open("/root/secret_file.txt", "r") as f:
      print(f.read())
except OSError as e:
   print("Caught OSError:", e)

We get the output as shown below -

Caught OSError: [Errno 13] Permission denied: '/root/secret_file.txt'

Here, the program fails to access the file due to permission restrictions, which raises the OSError.

Example: Creating a Directory That Already Exists

Trying to create a directory that already exists also raises an OSError -

import os

try:
   os.mkdir("my_folder")  # Try to create the same folder twice
   os.mkdir("my_folder")
except OSError as e:
   print("Caught OSError:", e)

The error obtained is as shown below -

Caught OSError: [Errno 17] File exists: 'my_folder'

In this example, the second call to os.mkdir() raises an OSError because the directory already exists.

Updated on: 2025-06-02T15:30:21+05:30

805 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements