Do Not Abuse Try Except In Python | by Christopher Tao | Towards Data Science

Like most other programming languages, 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 development. You will find that it is 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.
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.
Well, here we have only a few lines of code. It is not too difficult to realise the problem, perhaps. However, imagine that you are doing a project that has a much larger scale, the error message must be str, not int will not be very helpful for you to locate the problem.
The error message we can get from the exception object e is sometimes very limited. I would say that it does not always make sense in Python. In fact, the previous one is not too bad because at least it tells you why the error happened. Let’s see this one.
def f4(key):    try:        d = {'a': 1, 'b': 2}        return d[key]    except Exception as e:        print('Error: ', e)f4('c')
Of course, in this example we have only one line of code, we know what is the “c”. However, again, if this happens in a project, how could we troubleshoot the problem if we were only given an error message “c”?
Can you imagine that the case can be worse? Well, this one might not be 100% related to our topic, but I just want to present it because it can be potentially solved by the solutions in the later section.
Do you think it gonna be very safe if we put all of the code in the try block and catch all the generic exceptions in the except block? The answer is no. Otherwise, I will probably recommend using it everywhere :)
Let’s see this example.
def f5(num):    try:        return num*3    except Exception as e:        print('Error: ', e)num = f5('5')print('Result is', num)
Again, we define a very simple numerical computing function and pass a string into it. We might expect that the “exception” will be caught, but there is no exception.
Python is too flexible to have an error :)
If you want to try all your code and catch the exceptions, you can use the traceback library which is built-in Python. Let’s use the same examples as above shown.
import tracebackdef f4(key):    try:        d = {'a': 1, 'b': 2}        return d[key]    except Exception as e:        e = traceback.format_exc()        print('Error: ', e)f4('c')
Using traceback helped us to print more information about the error, so it will be easier for us to troubleshoot the problem. However, we need to import an extra library and write more code to do this.
Just need to think twice about whether it is worth doing this? Let’s see some other good manners.
This section is added just in case someone will say something like:
why use raise or assert? The full traceback stack will be simply displayed if you don’t use try ... except ... at all!
Indeed, this is what I want to say in this article. It is exactly the solution to the title “Do not abuse try ... except ... in Python”. The reason that I provide the two “solutions” below is just want to demonstrate what is the good manner.
As I said earlier, we should avoid using too much try ... except ... which can hide the exceptions. In contrast, we would like to have the exception reveal as much as possible. Using raise to manually raise an exception is one of a good manner.
Let’s modify our f1, f2 and f3 functions.
INVALID_NUM_EXCEPTION = Exception('The parameter must be integer!')def f1(num):    if type(num) != int:        raise INVALID_NUM_EXCEPTION    return (num+1)*2def f2(num):    if type(num) != int:        raise INVALID_NUM_EXCEPTION    return (num+1)*2def f3(num):    if type(num) != int:        raise INVALID_NUM_EXCEPTION    return (num+1)*2
Here, we defined an exception and raise it in the functions when the type of arguments passed in are not an integer.
Then, let’s run the same code to use these functions.
num1 = f1(5)num2 = f2('5')num3 = f3(5)
It is not too bad to meet an error if it tells you what is the error exactly and where did that happen.
Although assertion is more often used in testing, we can still use it during development to make sure that our code has fewer bugs. Also, it is usually kind of neat to use assertion than raising an exception, if we don’t care what’s the exact exception type.
INVALID_NUM_MSG = 'The parameter must be integer!'def f1(num):    assert isinstance(num, int), INVALID_NUM_MSG    return (num+1)*2def f2(num):    assert isinstance(num, int), INVALID_NUM_MSG    return (num+1)*2def f3(num):    assert isinstance(num, int), INVALID_NUM_MSG    return (num+1)*2
It is good to know more tricks in a programming language. I have to say that whenever I know something cool, I would also tend to use it. However, it also needs to think twice whether we need to do this and if that trick gives us more benefit than barriers.
Therefore, do not put all your code in the try ... except ... block in Python. Let the error reveal and make our life easier!
medium.com
If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)