Skip to Content

Python: “try-except-else” Usage Explained!

In this article, let us learn about the “try-except-else” mechanism in Python.

For those of you in a hurry here is the short version of the answer.

“try-except-else”: In a Nutshell

The try-except-else is a set of statements provided by Python to handle exceptions.

They each have a role and function as described in the following table:

tryHolds the code that might raise an exception
exceptHolds the code to be run in case the try block raises an error
elseHolds the code to be executed if the code in the try block did not raise any error.
Here’s how that would look in code:
try:
    # code that might raise an exception
except:
    # alternate code that will be executed when the code in the try clause is not executed
else:
    # code that will be executed if an exception is not raised in the try clause

Here is a simple example

try:
    print("This is the try block code")
except:
    print("This is the except block code")
else:
    print("This is the else block code")

This will produce the following output

This is the try block code
This is the else block code

Here the except block is not executed as no error was raised in the try block.

Here is another example where the try block raises an exception.

try:
    x = 1/0
    print("This is the try block code")
except:
    print("This is the except block code")
else:
    print("This is the else block code")

This will produce the following output.

This is the except block code

Here the except block is executed and the else block is not executed as the try block raised a ZeroDivisionError Exception.

The try-block does not print anything as it raises an exception on line-2 which causes the execution to jump to line-4 (skipping the print statement on line-3)

The best way to remember this is

If there is an exception then except block is executed

Elseelse” block is executed

embeddedinventor.com

Don’t worry if the above answer does not make sense to you as that was targeted at more experienced programmers who just wanted to refresh their memories. The rest of this article is dedicated to those of you in the first steps of your journey to becoming a Python Craftsman.

By the time you reach the end of this article, I suggest you come back and read this summary once more, I assure you it will make much more sense then!

“try-except-else”: A Thorough Explanation

I remember the time when I first came across the try-except-else structure in Python. I must say this combination of keywords was not intuitive at all for me to understand what was going on with the code. If you feel like you are sailing in the same boat, then this article is for you!

Let us start by breaking it down and taking a look at each of these keywords individually, starting with the try block:

try

The try block is the first of these blocks. We can place our code that might raise an error inside this block. 

We can use this by simply typing the keyword try and then placing the code inside its block:

try:
    #your code that might raise an error goes here

When an exception occurs in Python, the program is usually stopped. Look at this statement, it raises an error as we are not allowed to divide a number by 0, it is mathematically invalid:

x = 1/0

OUTPUT:

Traceback (most recent call last):
  File "/home/main.py", line 1, in <module>
    print(1/0)
ZeroDivisionError: division by zero

If you wish to learn the tricks behind utilizing the error text the right way to solve bugs, we have an excellent article written on that topic which you can find in the link below!

Python: Details contained in an Exception

Let’s use the same error-inducing code but with the try clause this time to see what will be different:

try:
    print(1/0)

You might ask what now?

Should we execute the above try block?

Not yet, python does not allow us to execute the try block by itself separately, we have to execute the except (or finally) block along with it, so let’s look into that shall we?

except

The except block is where we keep the code to be executed if the try block’s code raises an exception.

Let me say that again,

If the try block raises an error during execution, the Python interpreter will stop executing the code in the try block and jump to the except block.

If the code in the try block does not raise an error, the try block will finish executing and the except block will be skipped this time.

For visual learners:

The way to implement except is the same as try, just use the keyword and place the code inside its block.

Let’s look at two pieces of code that use except, one without an error and one with it:

Code without error

try:
	print ("Starting try block...")
	x = 10/5
	print ("The try-block has finished executing!")
except:
	print("Your code has an error in it!")

print("Exiting...")

OUTPUT

Starting try block...
The try-block has finished executing!
Exiting...

Here

  • the try-block finished executing without an error
  • lines 2 and 4 get printed in the output
  • except block is skipped since no exception was raised
  • the program exits printing line-8

Code with error

try:
	print ("Starting try block...")
	x = 10/0
	print ("The try-block has finished executing!")
except:
	print("Your code has an error in it!")

print("Exiting...")

OUTPUT

Starting try block...
Your code has an error in it!
Exiting...

Here

  • the try-block started executing
  • line-2: print (“Starting try block…”) ran without issues and we see that in the output.
  • line-3: x = 10/0 raised an exception as it is not possible to divide by zero.
  • Python stopped executing the try block and jumped to the except block.
  • line-6: print(“Your code has an error in it!”) gets executed and we see that in the output
  • the program exits printing line-8

I hope with this example the picture below makes much more sense!

It is worth mentioning that this section only scratched the surface of how to use the except block, if you wish to wield the power of except like a pro, I suggest setting 30mins time aside for the following articles!

Exceptions in Python: Explained for Beginners!

Python catch multiple exceptions

Python: “except Exception as e” Meaning Explained!

Alright, it’s time to move on to the last piece of the puzzle: the else block!

else

The else statement is an optional but a very handy keyword that we can use with the try-except statements.

The else block is closely related to the except block. The picture below shows their relationship.

Here is an easy way to remember this

If there is an exception then except block is executed

Elseelse” block is executed

embeddedinventor.com

Let us have a look at an example with all 3 keywords to see how they work together!

a = int(input("Please enter the first number: "))
b = int(input("Please enter the second number: "))
try:
    result = a/b
    print("Try block finished executing without an error")
except ZeroDivisionError:
    print("Error: Invalid input, you cannot divide a number by 0.")
else:
    print("result = ", result)

print("Exiting...")

OUTPUT#1: NO ERRORS

Please enter the first number: 8
Please enter the second number: 2
Try block finished executing without an error
result =  4.0
Exiting...

Here

  • a = 8 and b = 2
  • line-4 calculates the result to be 8/2 = 4
  • line-5 gets executed and prints “Try block finished executing without an error
  • except block is skipped as there was no exception raised in the try block
  • else block gets executed and the result is printed as 4.0
  • exits the program printing line-11

Now let us see what happens in case there is an error.

OUTPUT#1: EXCEPTION RAISED IN TRY BLOCK

Please enter the first number: 8
Please enter the second number: 2
Try block finished executing without an error
result =  4.0
Exiting...

This time

  • a = 8 and b = 0
  • line-4 in the try calculates tries dividing 8 by 0, but as you know dividing by zero is not allowed in math and this raises a ZeroDivisionError exception
  • Python then jumps to line-6, skipping line-5
  • prints the error message in line-7
  • skips the else block as this time there was an error
  • exits the program printing line-11

Now that we have mastered the topic of try-except-else, let us have another look at the table from the beginning of the article

tryHolds the code that might raise an exception
exceptHolds the code to be run in case the try block raises an error
elseHolds the code to be executed if the code in the try block did not raise any error.

I hope everything makes sense at this point!

There is one more keyword you need to learn which goes together with try, except, and else which is the finally keyword. We have covered that in another article, I suggest that one for your next read so that you can finally master all 4 of these awesome tools!

Python: “try-except-else-finally” Usage Explained!

And with that, I will end this article.

Congratulations on making it to the end of the article, not many have the perseverance to do so!

I hope you enjoyed reading this article and found it useful!

Feel free to share it with your friends and colleagues!

If your thirst for knowledge has not been quenched yet, here are some related articles that might spark your interest!

Related Articles

Python: Manually throw/raise an Exception using the “raise” statement

Python catch multiple exceptions

Python: Printing Exception (Error Message)

Python: “try-except-else-finally” Usage Explained!

Thanks to Namazi Jamal for his contributions in writing this article!