try-except vs If in Python

Python is a widely used general-purpose, high level programming language. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code. Python is a programming language that lets you work quickly and integrate systems more efficiently.

Most of the people don’t know that Try-Except block can replace if-else (conditional Statements). Yes, You read it right! It can be done. We can use Try ( Exception Handling ) instead of using normal conditional statements.

Here is a very famous example :



Using If

if key in mydict:
    mydict[key] += 1
else:
    mydict[key] = 1

Using try/except

try:
    mydict[key] += 1
except KeyError:
    mydict[key] = 1

It seems awsome right! But here comes the thing, Which code block works faster?
It can be measured using the timeit module in python. It can be seen whether Try block should be used instead of If.
Example: Time comparison for division of 2 numbers using try-except and if-else.

Below is the implementation.

filter_none

edit
close

play_arrow

link
brightness_4
code

import timeit
  
code_snippets =["""\
try:
    result = 1000 / value
except ZeroDivisionError:
    pass""",
"""\
if value:
    result = 1000 / value""",
]
  
for value in (1, 0):
    for code in code_snippets:
        t = timeit.Timer(stmt = code, setup ='value ={}'.format(value))
        print("----------------------")
        print("value = {}\n{}".format(value, code))
        print("%.2f usec / pass\n" % (1000000 * t.timeit(number = 100000)/100000))

chevron_right


Output:

----------------------
value = 1
try:
    result = 1000 / value
except ZeroDivisionError:
    pass
0.04 usec / pass

----------------------
value = 1
if value:
    result = 1000 / value
0.06 usec / pass

----------------------
value = 0
try:
    result = 1000 / value
except ZeroDivisionError:
    pass
0.37 usec / pass

----------------------
value = 0
if value:
    result = 1000 / value
0.01 usec / pass

Now it is clearly seen that the exception handler ( try/except) is comparatively faster than the explicit if condition until it met with an exception. That means If any exception throws, the exception handler took more time than if version of the code. That means the factor that decides the fastness of the code is the type of problem that is being handled.

We often hear that python always encourages EAFP(“It’s easier to ask for forgiveness than permission”) style over LBYL ( “Look before you leap ” ) style used in most of the languages like C. Python docs states that –

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

From our evaluation, we come to the following conclusion. Let’s consider our above example, if we expect that 99% of the cases the values of ‘value’ will not be equal to 0, we can use try/except approach. It will be faster if the exception really is exceptional. If the possibility of value becomes 0 is more than 50 %, then using ‘if’ is probably better.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Akanksha_Rai

Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.