Catch EnvironmentError Exception in Python



In Python, the EnvironmentError occurs when errors related to the system's environment, such as file I/O issues or hardware failures, occur. In the latest Python versions (i.e., 3.3+), this exception is the same as OSError.

In this article, you will learn how to catch EnvironmentError (or OSError) to handle system-level errors and prevent programs from crashing abruptly. Some of the common reasons to catch EnvironmentError are -

  • When a file operation fails
  • When a directory cannot be accessed or found
  • When a hardware or device-related issue occurs

Using try-except to Catch EnvironmentError

To catch EnvironmentError, use a try-except block and handle it just like any other exception. In Python 3.3 and above, it is recommended to catch OSError directly.

Example

In this example, the program tries to open a file that does not exist, which raises an EnvironmentError (OSError) -

try:
   with open("nonexistent.txt", "r") as f:
      content = f.read()
except EnvironmentError:
   print("EnvironmentError caught: File not found or cannot be opened.")

Following is the error obtained -

EnvironmentError caught: File not found or cannot be opened.

Using Exception Object for Details

You can capture the exception object to get more information about the error using the as keyword.

Example

The following example prints the actual error message from the exception object -

try:
   open("/invalid/path/sample.txt", "r")
except EnvironmentError as e:
   print("Caught EnvironmentError:", e)

We get the output as shown below -

Caught EnvironmentError: [Errno 2] No such file or directory: '/invalid/path/sample.txt'

EnvironmentError as Alias of OSError

In the latest Python versions (3.3+), EnvironmentError is the same as OSError. So, you can use either name, but OSError is preferred.

Example

Here, we catch OSError, which is functionally the same as EnvironmentError in recent Python versions -

try:
   open("missing_file.txt", "r")
except OSError:
   print("OSError caught: Problem accessing the file or resource.")

Following is the output obtained -

OSError caught: Problem accessing the file or resource.
Updated on: 2025-05-27T17:17:10+05:30

476 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements