When to use try-except instead of if-else?
When to use try-except instead of if-else?

When to Use Try-Except Instead of If-Else?

Programming is the process of defining a set of instructions that tells a machine how to perform a task. While executing these instructions we have to deal with certain constraints and conditions. These constraints or conditions decide the flow of our program. Based on these constraints the program decides whether the machine could complete a task and what will be the output. To check for these constraints in Python we use conditional statements (if-else) as well as try blocks (try-except). In this article, we will discuss how both of these work. We will also discuss the scenarios where we can use if-else and where we can use try-except. At last, we will try to answer the question mentioned in the title of this article.

Working of if-else Statements in Python

The if-else are conditional statements used in Python and other programming languages to control the flow of a program. They are also called decision-making statements as we use them for making decisions in our program.

The syntax of if-else statement is as follows.

if <expression>:
    <statement>
else:
    <statement>

In the above syntax, if the expression evaluates to be True then statements inside the if block are executed. Otherwise, the statement inside the else block is executed.

We use if-else statements to control the flow of the program based on known conditions. In other words, to use if-else we need to know the conditions in advance to prevent an error or exception.

Let’s take an example. Here we are defining a Python function findVal() that will take a python dictionary and a key as its arguments and will print the value related to that key.

def findVal(dictionary, key):
    print('key item:', key)
    print('Colour related to key item:', dictionary[key])
    print()

mydict = {'rose': 'red', 'cream': 'white', 'chocolate': 'brown'}

# calling function with key 'rose'
findVal(mydict, 'rose')
# calling function with key 'vanilla'
findVal(mydict, 'vanilla')

Output:

key item: rose
Colour related to key item: red

key item: vanilla
Traceback (most recent call last):
  File "c:\Users\Piyush\Desktop\Python Programs\try_if_comp.py", line 11, in <module>
    findVal(mydict, 'vanilla')
  File "c:\Users\Piyush\Desktop\Python Programs\try_if_comp.py", line 3, in findVal
    print('Colour related to key item:', dictionary[key])
KeyError: 'vanilla'

In the above example, we see that when we provided ‘vanilla‘ as a key to the function, an error occurred and the program ended abruptly. The error occurred because the key ‘vanilla‘ was not present in the dictionary. To avoid this error we can use an if-else statement as shown in the example below.

def findVal(dictionary, key):
    print('key item:', key)
    if key in mydict:
        print('Colour related to key item:', dictionary[key])
    else:
        print("key '{}' is not present in dictionary!".format(key))
    print()

mydict = {'rose': 'red', 'cream': 'white', 'chocolate': 'brown'}

# calling function with key 'rose'
findVal(mydict, 'rose')
# calling function with key 'vanilla'
findVal(mydict, 'vanilla')

Output:

key item: rose
Colour related to key item: red

key item: vanilla
key 'vanilla' is not present in dictionary!

In the above example, we are using the if statement to check whether the key is present in the dictionary. Here, in the first function call, the specified key is present in the dictionary so the function is printing its corresponding value. In the second function call, the specified key is not present in the dictionary. Now, instead of throwing an error, the function is displaying the message that the key is not present and exits normally. This program ended perfectly unlike the program without condition checks. This is the working of if-else statements. It prevented the program from error by checking for certain conditions in advance.

Suggested Reading: Python If Else Shorthand

Working of try-except in Python

The try-except blocks are used for exception handling in Python. An exception is an event that occurs during the execution of a program and results in an interruption in the flow of the program. An exception is nothing but an error that occurs during runtime. It occurs when our code fails to satisfy certain constraints or conditions. We use try-except construct to handle exceptions.

The syntax of try-except statement is as follows.

try:
    # block of code
except <exception>:
    # code executed when there is an exception

Statements or parts of code written inside the try block are executed as usual. If any exception arises, the control goes to except block and part of the code written inside it is executed.

Now, let’s see our previous example on extracting a value using a key from a dictionary once again. Here, we will be using try-except instead of if-else.

def findVal(dictionary, key):
    print('key item:', key)
    try:
        print('Colour related to key item:', dictionary[key])
    except KeyError:
        print("KeyError: '{}' is not present in dictionary!".format(key))
    print()

mydict = {'rose': 'red', 'cream': 'white', 'chocolate': 'brown'}

# calling function with key 'rose'
findVal(mydict, 'rose')
# calling function with key 'vanilla'
findVal(mydict, 'vanilla')

Output:

key item: rose
Colour related to key item: red

key item: vanilla
KeyError: 'vanilla' is not present in dictionary!

Here, the output is similar to what we have seen using the if-else statement. However, internal working is different than that of if-else. In the case of if-else, the condition was pre-checked and it prevented the error or exception from happening. But in the case of try-except, the except block handles the error after it has occurred. That’s the major difference between both constructs.


Advantage of try-except over if-else

  • We can use try-except for exception handling (handling system-generated errors) as well as for checking conditions whereas, we can use if-else only for checking conditions and it is unable to handle exceptions or system-generated errors.
  • We can use a single try block to check for several conditions and errors but in the case of an if-else statement, we may need to have an if-else block for each condition. However, multiple conditions can be specified using if but in that case else parts of all would be the same.
  • try-except statement works faster than an if-else statement when the possibility of an exception is very low.

Advantage of if-else over try-except

  • if-else statements prevent the error from occurring by checking for the conditions (that may cause an error) in advance. Whereas try-except waits for an error to occur and handles it afterward. Although try-except statements are faster but if-else statements are faster and more efficient when there is an equal possibility of an exception.

Suggested Reading: Command Line Arguments Using sys.argv List in Python


When to use if-else in Python?

We should use if-else statements when we know the constraints and conditions in advance. Also, if there is an equal possibility that a condition may or may not be true, it’s better to use if-else rather than try-except. In such cases if-else proves to be much faster and more efficient.

When to use try-except in Python?

We should use try-except when we don’t know about a condition or constraint that may cause an error. To handle unknown errors and indeterminable conditions we need to use try-except blocks. Also, in most of the cases when there is very little possibility of a condition being false, we should use try-except as they are much faster and more efficient.

Apart from checking errors and conditions, try-except statements are used for many operations in Python. We often use try-except in file-handling operations, database-related operations, and while using Python frameworks. The use of try-except proves to be extremely beneficial in such cases as it prevents errors that may result in data loss, undesirable outputs, and unexpected terminations.

Conclusion

In this article, we have discussed the working of the if-else statements as well as the try-except statement. We have also discussed their advantages over each other and which one to use in different cases. Having read these, we can now answer our question that when to use try-except instead of if-else. So, we can say that whenever we are uncertain of errors or conditions that may lead to an exception, in that case, we should use try-except instead of if-else. Other than this we should use try-except when the possibility of exception is very little as they are faster and more efficient than the if-else. To study more topics in Python, you can read an article on list comprehension or an article on functions in Python.

Donate to Avid Python

Dear reader,
If you found this article helpful and informative, I would greatly appreciate your support in keeping this blog running by making a donation. Your contributions help us continue creating valuable content for you and others who come across my blog. 
No matter how big or small, every donation is a way of saying "thank you" and shows that you value the time and effort we put into writing these articles. If you feel that our article has provided value to you, We would be grateful for any amount you choose to donate. 
Thank you for your support! 
Best regards, 
Aditya
Founder

If you want to Pay Using UPI, you can also scan the following QR code.

Payment QR Code
Payment QR Code

Piyush Sharma

Third-year computer engineering student inclined towards the latest trends and technology. Always keen to explore and ready to learn new things. To read more articles on Python, stay tuned to avidpython.com.

Leave a Reply