The Wayback Machine - https://web.archive.org/web/20240810170254/https://www.geeksforgeeks.org/try-except-vs-if-in-python/
Open In App

try-except vs If in Python

Last Updated : 13 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 awesome 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.

Python3




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))


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.



Similar Reads

Connectionerror - Try: Except Does Not Work" in Python
Python, a versatile and powerful programming language, is widely used for developing applications ranging from web development to data analysis. However, developers often encounter challenges, one of which is the "ConnectionError - Try: Except Does Not Work." This error can be frustrating as it hinders the robustness of your code, especially when d
4 min read
Try, Except, else and Finally in Python
An Exception is an Unexpected Event, which occurs during the execution of the program. It is also known as a run time error. When that error occurs, Python generates an exception during the execution and that can be handled, which prevents your program from interrupting. Example: In this code, The system can not divide the number with zero so an ex
6 min read
Python Try Except
Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program.Note: For more information, refer to Errors and Exceptions in PythonSome o
6 min read
Python Program to Removes Every Element From A String List Except For a Specified letter
Given a List that contains only string elements, the following program shows methods of how every other alphabet can be removed from elements except for a specific one and then returns the output. Input : test_list = ["google", "is", "good", "goggled", "god"], K = 'g' Output : ['gg', '', 'g', 'ggg', 'g'] Explanation : All characters other than "g"
4 min read
Python | Remove all characters except letters and numbers
Given a string, the task is to remove all the characters except numbers and alphabets. String manipulation is a very important task in a day to day coding and web development. Most of the requests and responses in HTTP queries are in the form of Python strings with sometimes some useless data which we need to remove. Remove all characters except le
4 min read
Python - Generate random number except K in list
Sometimes, while working with python, we can have a problem in which we need to generate random number. This seems quite easy but sometimes we require a slight variation of it. That is, we require to generate random number from a list except K. Lets discuss certain ways in which this task can be performed. Method #1: Using choice() + list comprehen
3 min read
Python | Generate random number except K in list
Sometimes, while working with Python, we can have a problem in which we need to generate random numbers. This seems quite easy but sometimes we require a slight variation of it. That is, we require to generate random numbers from a list except K. Let's discuss certain ways in which this task can be performed. Method #1 : Using choice() + list compr
6 min read
Python | Extract characters except of K string
Sometimes, while working with Python strings, we can have a problem in which we require to extract all the elements of string except those which present in a substring. This is quite common problem and has application in many domains including those of day-day and competitive programming. Lets discuss certain ways in which this task can be performe
6 min read
Python program to Replace all Characters of a List Except the given character
Given a List. The task is to replace all the characters of the list with N except the given character. Input : test_list = ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T'], repl_chr = '*', ret_chr = 'G' Output : ['G', '*', 'G', '*', '*', '*', '*', '*', '*'] Explanation : All characters except G replaced by * Input : test_list = ['G', 'F', 'G', 'B', 'E
4 min read
Python - Reverse String except punctuations
Given a string with punctuations, perform string reverse, leaving punctuations at their places. Input : test_str = 'geeks@#for&%%gee)ks' Output : skeeg@#rof&%%ske)eg Explanation : Whole string is reversed, except the punctuations. Input : test_str = 'geeks@#for&%%gee)ks' [ only substring reversal ] Output : skeeg@#rof&%%eeg)sk Expla
6 min read
Practice Tags :
three90RightbarBannerImg