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

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

Handling is good but using . The use of exception wildcard exceptions can cause big problems 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 . But when we run this code the actual output will be Cannot divide using zerotext exception was not intended .

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 if and only if the actual exception is except block . ZeroDivisionError

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

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/

Originally published at https://parseltongue.co.in on September 3, 2021.

Coding, Reading,Python