Common mistakes we make in Python and why we should avoid that part 4

Posted by Afsal on 03-Sep-2021

Hi Pythonistas!

This is part 4 of the common mistakes series. Today we are going to discuss a mistake that can cause us a big headache.

Wildcard try-except:

Handling exception is good but using wildcard exceptions can cause big problems. The use of wildcard exceptions can lead to the suppression of some exceptions which we may not intend to do. Consider the below example.

def divide(first, second):

    try:
        result = first/second
        print(result_var)
    except:
        print(“Cannot divide using zero”)

Here in the above example, I intended to handle the ZeroDivisionError. But unknowingly  I wrote result_var instead of result. Handling this exception was not intended. But when we run this code the actual output will be "Cannot divide using zero" text.

What is the solution:

Instead of doing a wildcard exception, handle the specific exception that we actually intend to do.  It will save us from big trouble.

def divide(first, second):
    try:
       result = first/second
       print(result_var)
    except ZeroDivisionError:
        print(“Cannot divide using zero”)
Traceback (most recent call last):
  File "wildcard_exception.py", line 13, in <module>
    divide(1, 3)
  File "wildcard_exception.py", line 7, in divide
    print(result_var)
NameError: name 'result_var' is not defined

Here, while we run the code, the program will throw an exception and will only go to the except block if and only if the actual exception is ZeroDivisionError.

When catching an exception always remember these lines of zen of python

Errors should never pass silently.

Unless explicitly silenced.

Happy coding!!

Check out the previous posts of this series, if not already done!

https://parseltongue.co.in/common-mistakes-we-make-in-python-and-why-we-should-avoid-that/

https://parseltongue.co.in/common-mistakes-we-make-in-python-and-why-we-should-avoid-that-part-2/

https://parseltongue.co.in/common-mistakes-we-make-in-python-and-why-we-should-avoid-that-part-3/