Like most of the other programming language, Python supports catching and handling exceptions during runtime. However, sometimes I found that it has been overused.

It turns out that some developers, especially those who are newbies in Python, tend to use try … except … a lot, once they found such a feature. However, I would say that we should try to avoid using that if possible, especially during the early stage of the development. You will find that it is actually better to let the problem reveal, rather than hide it.

In this article, I will demonstrate some examples to show how try … except … can create problems and what is the better manner in Python programming.

Problem Definition

Image for post

Photo by geralt on Pixabay

Let’s start with a problematic example, which is a very typical scenario that I have seen.

def f1(num):
    try:
        return (num+1)*2
    except Exception as e:
        print('Error: ', e)
def f2(num):
    try:
        return (num+1)*3
    except Exception as e:
        print('Error: ', e)
def f3(num):
    try:
        return (num+1)*4
    except Exception as e:
        print('Error: ', e)

We have three functions that do some simple numerical calculations. All of them are implemented with try … except … with everything. Then, we want to use them in our code as follows.

num1 = f1(5)
num2 = f2('5')
num3 = f3(5)

Please note that I deliberately pass a string “5” in the second function, because I just want to create an exception artificially. The result we have is as follows.

Image for post

Well, here we have only a few lines of code. It is not to difficult to realise the problem, perhaps. However, imagine that you are doing a project has a much larger scale, the error message must be str, not int will not be very helpful for you to locate the problem.

Another Example

Image for post

Photo by guvo59 on Pixabay

#programming #python

Do Not Abuse Try Except In Python
3.25 GEEK