How to Ignore Exceptions the Pythonic Way?

If you are an application developer, you might have to implement an error-free code that is well tested. In my instances, we would like to ignore I/O or Numerical exceptions. In this blog post, you will learn how we can safely ignore exceptions in Python.

Imagine you are working on an application  where you have a list of numbers and would like to output the reciprocal of the numbers. If by mistake the list consists of 0, then the program would crash since we are diving 1 by 0 which will raise an exception. We can implement this in a bug free manner by using a try and except block.

We can achieve this by the following two steps

  1. Put the logic of taking the reciprocal of the number inΒ try block
  2. Implement an exception block that is executed wherever the number is 0. Continue with the rest of the logicΒ 

Without a try-except Block

Let us first implement the logic using a simple for loop. As you can see in the output below, the program crashed when the number was 0

numbers = [12, 1, 0, 45, 56]
for number in numbers:
    print('result is {}'.format(1/number))

Output

result is 0.08333333333333333
result is 1.0

---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-27-c1f2d047aa92> in <module>()
      1 for number in numbers:
----> 2   print('result is {}'.format(1/number))

ZeroDivisionError: division by zero
ο»Ώ

With a try-except Block

Let us now see how we can safely ignore an exception

numbers = [12,1,0,45,56]
for number in numbers:
    try:
        print('result is {}'.format(1/number))
    except Exception as e:
        print('Ignoring Exception', e)

Output

result is 0.08333333333333333
result is 1.0
Ignoring Exception division by zero
result is 0.022222222222222223
result is 0.017857142857142856

Summary

In this blog post you learned how to safely ignore exceptions in Python. You learnt how to use a try and except block and continue with the program if an exception is encountered.