Python Exception Handling

Python Exception Handling

Table of Contents

An exception is a kind of error that occurs at runtime. Exceptions are different from errors as some of them can be dealt with without the program crashing. For instance, if you write a program to divide two numbers from a user. You must ensure that the denominator is not 0 as a number divided by zero is not defined. 

But rather than the user’s input crashing your program, you could raise an exception that warns the user about the denominator being a non-zero number. General errors such as syntax errors cannot be dealt with in such a manner as the program is bound to crash when encountered. In this tutorial, we will discuss how to handle exceptions in Python using keywords such as try, except, raise, finally. By the end of this tutorial, you will learn:

  • Common Exceptions in Python
  • Why Using Exceptions is Important
  • Using the Try and Except Statements to Handle Exceptions
  • Using the Finally Statement 
  • Using the raise Statement

Common Exceptions in Python

  • AssertionError: This is raise when an assert statement is not true
  • AttributeError: This is raised when the assignment of a reference or attribute fails. 
  • FloatingPointError: This is raised when a floating-point operation fails.
  • ImportError: This is raised when the module you want to import is not found
  • IndexError: This is raised when the index of an iterators runs out of range
  • MemoryError: This is raised when your system runs out of memory. Maybe in an infinite loop for instance. 
  • NameError: This is raised when a variable to be used is not defined
  • ValueError: This is raised when a function receives an incorrect value as an argument even if the datatype was correct
  • ZeroDivisionError: This is raised when the denominator of a division operation is zero. 

Why Using Exceptions is Important

  • With errors, you can set apart error handling codes from normal code
  • It prevents your code from crashing completely
  • It makes your code readable by others
  • It guides the programmer on the kind of inputs to expect from the end-users
  • You can raise your exception using the raise statement 

Using the Try and Except Statements to Handle Exceptions 

Errors are generally handled using the try and except statement. The codes in the try block are codes that you may accept some errors during runtime and want to handle. Let’s see a simple example. We will write a code that receives 2 numbers from a user and then divides them.

#the program divides a by b
a = float(input('Enter the numerator: '))
b = float(input('Enter the denominator: '))
 
result = a / b
 
print(f"{a} / {b} = {result}")
print('Done with the program')

Let’s say, the user enters 7 as numerator and 2 as the denominator.

Output:
Enter the numerator: 7
Enter the denominator: 2
7.0 / 2.0 = 3.5
Done with the program

All ran smoothly. But a user may enter 0 as the denominator. Assuming the user enters 7 and 0. What would be the output?

Enter the numerator: 7
Enter the denominator: 0
Traceback (most recent call last):

  File “c:/Users/DELL/Desktop/pycodes/__pycache__/strings.py”, line 17, in <module>    
result = a / b
ZeroDivisionError: float division by zero

It throws an error. Notice that the last line of code ‘Done with the program’ was not printed. This means that the code has stopped abruptly at the point where the exception was encountered. In reality, this is not a good way of writing codes as a user’s error can completely mar the code from performing any task. 

When you place the code in a try block, the Python interpreter knows that you wish to handle exceptions encountered. The except block indicates the error you want to track and the kind of message you wish to print. 

Let’s have the syntax of the try and except statement.

try:
    #insert the block of code
    
except Exception:
    #insert the kind of message to be printed

Now, let’s put the error code inside a try-except block to handle the ZeroDivisionError.

#the program divides a by b
a = float(input('Enter the numerator: '))
b = float(input('Enter the denominator: '))
 
try:
    result = a / b
    print(f"{a} / {b} = {result}")
 
except Exception as e:
    print(e)
    print()
    print('Please enter a non-zero digit to fix this error')
 
print('Done with the program')
Output:
Enter the numerator: 7
Enter the denominator: 0
float division by zero

Please enter a non-zero digit to fix this error

Done with the program

Observe the output. It says float division by zero. Then print my custom message, ‘Please enter a non-zero digit to fix this error’. Lastly, it runs the last line of code, ‘Done with the program’. This shows that the code was run completely even with the error. 

Alternatively, you may specify the type of error you are expecting and write a custom message. For instance, I can write except ZeroDivisionError rather than except Exception as e. This is a much better way of handling errors as it specifies the kind of error to catch. Let’s change our code slightly to reflect the ZeroDivisionError.

#the program divides a by b
a = float(input('Enter the numerator: '))
b = float(input('Enter the denominator: '))
 
try:
    result = a / b
    print(f"{a} / {b} = {result}")
 
except ZeroDivisionError:
    print('Please enter a non-zero digit to fix this error')
 
print('Done with the program')
Output:
Enter the numerator: 7
Enter the denominator: 0
Please enter a non-zero digit to fix this error
Done with the program

Using the Finally Statement 

Codes that you want to get run whether or not an error was encountered are placed in the finally block. For instance, if you are dealing with a file or database and you want such a database to be closed as the last step. The code should be placed in the finally block. 

In our previous examples, the last line of code where we printed ‘Done with the program’ can be placed in a finally block because we want this code to be run no matter what. Let us tweak the code further. 

#the program divides a by b
a = float(input('Enter the numerator: '))
b = float(input('Enter the denominator: '))
 
try:
    result = a / b
    print(f"{a} / {b} = {result}")
 
except ZeroDivisionError:
    print('Please enter a non-zero digit to fix this error')
 
finally:
    print('Done with the program')
Output:
Enter the numerator: 7
Enter the denominator: 0
Please enter a non-zero digit to fix this error
Done with the program

As seen the result is like the previous. This is however a cleaner way of writing Python codes. 

Using the raise Statement

The raise statement is used for creating exceptions on your own. If you wish to handle an error when something happens, you can state the condition with an if statement, then write how you wish to handle the error in the raise block. See the syntax below. 

try:
#     some code is entered here
    if (#state some condition):
        raise #do something

Let’s use the raise statement in our earlier code.

#the program divides a by b
a = float(input('Enter the numerator: '))
b = float(input('Enter the denominator: '))
 
try:
    result = a / b
    print(f"{a} / {b} = {result}")
    if b == 0.0:
        raise ZeroDivisionError
 
finally:
    print('Done with the program')
Output:
Enter the numerator: 7
Enter the denominator: 0.0
Done with the program
Traceback (most recent call last):
  File "c:/Users/DELL/Desktop/pycodes/__pycache__/strings.py", line 16, in <module>
    result = a / b
ZeroDivisionError: float division by zero

As seen, the exception was raised while the code in the finally block was run. 

In Summary, 

You have seen the importance of exception handling in Python and how to do it. You learned about using the try, except, raise statement and how they function. Also, you discovered the various exceptions you have in Python. Although the code example here focused on ZeroDivisionError, it is pretty much the same process for other types of exceptions. If you have any questions, feel free to leave them in the comment section and I’d do my best to answer them.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share this article
Subscribe
By pressing the Subscribe button, you confirm that you have read our Privacy Policy.
Need a Free Demo Class?
Join H2K Infosys IT Online Training
Enroll Free demo class