Handling Built-in Exception IOError in Python (With Examples)

Handling Built In Exception IOError In Python

In Python 2, whenever we are performing an I/O operation and it fails, an exception is thrown called IOError.

Error is an invalid code that stops the execution of the program, for instance, syntax error, logical error, type error, etc. At the same time, an exception is an error that occurs during the execution of a program and interrupts the flow of the program. IOError is also a type of exception in Python. 

In this Python tutorial, we will learn when the IOError occurs, Identify an IOError and how to handle it.

Python IOError Exception

IOError exception is raised when an input or output operation is taking place, there can be many reasons for this.

Below are the reasons that cause the IOError:

  • The file a user tried to access does not exist
  • The user does not have permission to access the file
  • File already in use
  • The device is running out of space to process

There may be other reasons, but these are the most commonly seen reasons.

Check: Exceptions in Python

Identify IOError in Python

We can identify the IOError by looking at the command line. When an IOError occurs, the Python’s interpreter throws a traceback message with the name and description of the exception.

For example, if we execute the code below, see the error message we get.

with open("hello.py", "r") as f:
    content = f.read()

Output:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    with open("hello.py", "r") as f:
IOError: [Errno 2] No such file or directory: 'hello.py'

Here we can see that the interpreter has already mentioned IOError with a message that “No such file or directory: ‘hello.py'” as “hello.py” does not exist.

So how do we handle this error?

Handling IOError in Python

The IOError can be handled by using try except block, which is the most common way for exception handling in Python. The try block contains the code that can cause an exception whereas the except clause will contain the code that executes if the IO error occurred. A try block can have more than one except clause, to specify handlers for multiple exceptions at a time.

Syntax:

try:
    # code that raise IOError
except IOError:
    # code to handle IOError

Examples of Handling IOError in Python

Let’s look at some examples of exception handling.

Example 1:

In this example, we will try to handle the exception when a user attempt to read a file that does not exist. We have written a print statement to display a user-friendly error message so that the user knows the reason why the file name “hello.txt” is unable to open.

try:
    with open("hello.txt", "r") as f:
        content = f.read()
except IOError:
    print("The file you are trying to access does not exist")

Output:

The file you are trying to access does not exist

Example 2:

Let’s see an example of handling IOError while performing a write operation.

try:
    with open("hello.txt", "r") as f:
        f.write("Hello World!")
except IOError:
    print("The file in which you are trying to write does not exist")

Output:

The file in which you are trying to write does not exist

Example 3:

Now, let’s handle the exception that occurs when the network resource we are trying to access is unavailable. Here we have also printed the actual error message.

import urllib2

try:
    response = urllib2.urlopen("http://example.com")
    html = response.read()
except IOError as e:
    print("An IOError occurred: %s" % e)

Output:

An IOError occurred: <urlopen error [Errno -3] Temporary failure in name resolution>

Conclusion

In this tutorial, we have seen that sometimes when we are trying to read or write on a file that does not exist or the user does not have permission to access the file or the file is already in use or the device is running out of space for the operation, an IOError exception occurs.

This IOError can be handled using a try-except block, just like any other exception. For handling, one can print the user-friendly message when the exception is thrown or write further code for alternate execution in the except clause. Hope now you have got enough idea about IOError and its handling in Python.

Reference

https://docs.python.org/3/tutorial/errors.html