Python – Exception Handling

With the help of examples, you’ll learn how to manage exceptions in your Python program using try, except, and finally statements.

Exceptions in Python

When your program detects an error, Python raises a number of built-in exceptions (something in the program goes wrong).

When one of these exceptions occurs, the Python interpreter suspends the current process and sends control to the caller process until the problem is resolved. The program will crash if it is not handled properly.

Consider a software in which function A calls function B, which in turn calls function C. If an exception occurs in function C but isn’t handled there, the exception is passed to B, who then passes it on to A.

If the error is not addressed, an error notice appears and our program comes to an abrupt halt.


Catching Exceptions in Python

Exceptions in Python can be managed with the try statement.

The try clause contains the critical operation that can cause an exception. The except clause contains the code that handles exceptions.

As a result, once we’ve caught the exception, we may choose which operations to conduct. Here’s an easy example.

# import module sys to get the type of exception
import sys

randomList = ['a', 0, 2]

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except:
        print("Oops!", sys.exc_info()[0], "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)

Output

The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5

We loop through the values of the randomList list in this application. As previously stated, the try block contains the code that can produce an exception.

If there is no exception, the except block is bypassed, and normal flow resumes (for last value). However, if an exception happens, the except block will catch it (first and second values).

Using the exc info() function in the sys module, we print the name of the exception. We can see that 0 causes ZeroDivisionError and a causes ValueError. Ad

Because every exception in Python is derived from the fundamental Exception class, we may also accomplish the operation as follows:

# import module sys to get the type of exception
import sys

randomList = ['a', 0, 2]

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except Exception as e:
        print("Oops!", e.__class__, "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)

This program has the same output as the above program.


Catching Specific Exceptions in Python

We didn’t identify any specific exceptions in the except clause in the preceding example.

This isn’t a smart programming approach because it will capture all exceptions and treat each instance the same. We can indicate which exceptions should be caught with an except clause.

If an exception occurs, a try clause can have any number of except clauses to handle distinct occurrences, but only one will be performed.

In an except clause, we can declare several exceptions by using a tuple of values. The following is an example of pseudo code.

try:
   # do something
   pass

except ValueError:
   # handle ValueError exception
   pass

except (TypeError, ZeroDivisionError):
   # handle multiple exceptions
   # TypeError and ZeroDivisionError
   pass

except:
   # handle all other exceptions
   pass

Raising Exceptions in Python

Exceptions are produced in Python programming when runtime issues occur. The raise keyword can also be used to manually raise exceptions.

We can optionally pass values to the exception to provide more information about why it was raised.

>>> raise KeyboardInterrupt
Traceback (most recent call last):
...
KeyboardInterrupt

>>> raise MemoryError("This is an argument")
Traceback (most recent call last):
...
MemoryError: This is an argument

>>> try:
...     a = int(input("Enter a positive integer: "))
...     if a <= 0:
...         raise ValueError("That is not a positive number!")
... except ValueError as ve:
...     print(ve)
...    
Enter a positive integer: -2
That is not a positive number!

Python try with else clause

In some cases, you may want to run a specific section of code if the code block inside attempt completed successfully. You can utilize the optional else keyword with the try statement in these circumstances.

The preceding unless clauses do not handle exceptions in the else clause.

Consider the following scenario:

# program to print the reciprocal of even numbers

try:
    num = int(input("Enter a number: "))
    assert num % 2 == 0
except:
    print("Not an even number!")
else:
    reciprocal = 1/num
    print(reciprocal)

Output

If we pass an odd number:

Enter a number: 1
Not an even number!

If we pass an even number, the reciprocal is computed and displayed.

Enter a number: 4
0.25

However, if we pass 0, we get ZeroDivisionError as the code block inside else is not handled by preceding except.

Enter a number: 0
Traceback (most recent call last):
  File "<string>", line 7, in <module>
    reciprocal = 1/num
ZeroDivisionError: division by zero

Python try…finally

In Python, a finally clause can be added to the try statement. This clause is always executed and is commonly used to release external resources.

For example, we could be working with a file or a Graphical User Interface while connecting to a remote data center via the network (GUI).

Regardless of whether the program ran successfully or not, we must clear up the resource before the program comes to a halt. To ensure execution, these activities (closing a file, launching a GUI, or disconnecting from the network) are performed in the finally clause.

To illustrate this, consider the following file operations example.

try:
   f = open("test.txt",encoding = 'utf-8')
   # perform file operations
finally:
   f.close()

Even if an exception occurs during program execution, this type of construct ensures that the file is closed.

Leave a Comment

Your email address will not be published.