Python: Details contained in an Exception


In this article we’ll try to understand how to read an exception message and learn how to use the details/clues that are part of the exception message to debug our code effectively.

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

Details in an Exception Message: In a Nutshell

When you encounter an error in Python, you get a message packed with several details about the error.

The technical name of the entire error message is “Traceback” and its 3 main parts are

  1. Stack Trace – helps you find in which part of the code the error occurred 
  2. Exception Name – Says what type of exception has occurred &
  3. Exception message – A short message explaining what the error was.

The figure below shows all 3 parts of the Error Message.

Details contained in an Exception

If this short explanation leaves you confused don’t worry as this was aimed at people who are already familiar with the concepts and are just looking to refresh their memories.

The rest of the article is written from a beginners perspective and is focused on answering the following questions

  • What is “Stack-Trace”? Why that matters?
  • What does Exception Message and Exception Name tell us?
  • How to use the above information to effectively debug your Python code?

I suggest you find someplace quiet and focus for the next 10 minutes and read on!

For visual learners out there we have also made an interesting video on this topic of how to use the different details contained in an exception to solve bugs in python!

You can only cover so much in a video, read on for a more thorough explanation on the topic of details covered in an exception message!

Details in an Exception Message: A Thorough Explanation!

Exceptions in Python are events that interrupt the normal flow and execution of a program. This happens when your Python interpreter faces an unexpected scenario and does not know how to deal with it.

If you are thinking you can use a refresher on the fundamentals of Exceptions in python, then I suggest reading our other article Exceptions in Python before continuing this one.

When an error message pops up, you would have noticed there is quite a lot of information there. On one hand, this huge wall of text can be disappointing as our code just crashed, on the other hand, it can get rather overwhelming to read and understand what went wrong, unless we specifically know what to look for.

The first thing we need to do is understand is the purpose of the error message, it is not to scare us, Python is simply telling us

Hey! Sorry, I ran into some unexpected situation and I cannot continue executing your code, here are some clues on how to fix your code!

embeddedinventor.com

The technical name for this “big wall of text” is Traceback and it consists of 3 main parts. They are

  1. Stack trace– helps you find in which part of the code the error occurred 
  2. Exception name– Says what type of exception has occurred
  3. Exception message – A short message explaining what the error was.

Let us start with the easiest and most useful of the three: “The Exception Message”

Exception Message

The Exception Message is present on the last line of the Traceback (the huge wall of text), so this is the first place we should look. It is a short handy message that briefly describes the problem we’re facing.

For example consider the following line of code

x = 7/0

This line will fail with the following text

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

If you look at the very last part of this text, you will see the Exception message “division by zero” which tells us that in our code we made a “division by zero”, and as you know, in math, division by zero is not allowed! Now that we know what the error is, we can go back to the code and fix that!

If you wish to learn how to log just this Exception Message, here is an article with code snippets to do just that!

Print just the message of an exception

This is a rather simple case and the Exception message is probably enough to fix the bug. What if you read the message and you have no clue what it means? That’s where the other parts of the Traceback comes in handy!

Lets look at the next important part the Exception Name!

Exception Name

Exception Name is the very 1st word of the last line of the error text. This is also known as the “Exception Type

In the above example, this is “ZeroDivisionError”, all you need to do is just search the web for this word, and I assure you, that you will find plenty of resources explaining what exactly this error means and where to start looking!

Let us take another example and see how the Exception Name looks like

alphabets = {"a":1, "b":2, "c":3, "d":4}
print(alphabets["e"])

Running this code will give the following error text

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(alphabets["e"])
KeyError: 'e'

The first word in the last line is the Exception Name or Exception Type: “KeyError”

If this is one of the errors you face regularly, be sure to checkout our article on KeyErrors here.

If you wish to learn how to log just this Exception Name, here is an article with code snippets to do just that!

Python: Printing Exception Type

Stack Trace

If you are hearing the term “Stack Trace” for the 1st time, do not let the technicality of the name get in your way, Stack-Trace is just the trail of bread-crumbs to help you track-down the spot in code where the error has occurred.

Let us look at an example of Stack-Trace.

weather = "Sunny"
time = "1:00 P.M"

print ("The weather is " + weather + " and the time is " + time + " over here in " + place)

Running this code will lead to an Exception with the following output.

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    print ("The weather is " + weather + " and the time is " + time + " over here in " + place)
NameError: name 'place' is not defined

As you can see, we forgot to add the place string and we ran into NameError.

If you take a closer look at lines 2 and 3 in the output above,

  File "main.py", line 4, in <module>
    print ("The weather is " + weather + " and the time is " + time + " over here in " + place)

It says in line number 4 of the file “main.py” there is an error. Combining this information with the last line which says “NameError: name ‘place’ is not defined” we can see that the error was that there is no variable named “place” in our code and that lead to the error.

The above example is fairly simple with just 4 lines of code, but if you take any real-world project, you will have 10s of files with 1000s of lines of code in them and the Stack-Trace is really useful in figuring out which of these 1000 lines the error actually is in!

If you wish to learn how to log just this StackTrace, here is an article with code snippets to do just that!

Python: Print StackTrace on Exception!

Traceback

Time to put all the 3 parts together!

As we saw previously, Traceback is just the technical name for the combination all 3 parts we saw previously!

It’s called a Traceback message as you can use it to trace it back to the error in your code

Lets have a look at another example, this time a more complicated one and look at the entire Traceback (the error text)!

def function2():
    return 1/0
    
def function1():
    print(function2())
   

function1()

What I’ve done is written a function that is bound to produce an error, the function2()
Then I used another function, function1() that just prints the contents of our error laden function. 

Now let’s see how things workout this time shall we?

Traceback (most recent call last):
  File "main.py", line 8, in <module>
    function1()
  File "main.py", line 5, in function1
    print(function2())
  File "main.py", line 2, in function2
    return 1/0
ZeroDivisionError: division by zero

Lets us take a look at the entire error message line by line. The first line as shown below is simply the “header” telling us that

An error has occurred and the text below contains clues on where the error is!

Traceback (most recent call last):


After that lets quickly jump to the last line and see what the error is

ZeroDivisionError: division by zero

As you can see, somewhere in our code we made the mistake of dividing by Zero, which resulted in the appropriately named “ZeroDivisionError

Now it is time to figure out where the error has occurred using the StackTrace/”middle portion” of the Traceback (the error text)!

  File "main.py", line 8, in <module>
    function1()
  File "main.py", line 5, in function1
    print(function2())
  File "main.py", line 2, in function2
    return 1/0

Conveniently our dear friend StackTrace helps us debug our code in this scenario by unfolding everything line by line.

Here the stack trace is showing us the sequence of calls in the order line-8 of main.py -> function2 -> function1

With these many breadcrumbs leading our way, solving the mystery of what the error is and where it is should be a piece of cake!

There is a nice trick to do this efficiently, lets see that shall we!

How to read a Traceback message?

You might think that you can read the message line by line from top to bottom as usual, but it is actually recommended that you read Traceback messages from bottom to top!

The following picture summarizes the order in which I prefer reading the exception message

To put it in words

  1. First read the Exception Message, sometimes this is all you need to solve the issue
  2. If the Exception Message does not make much sense then google the Exception Name and understand what it means
  3. Once you have a good understanding of what error has occurred, use the StackTrace to figure out where the error is!

Conclusion

In this article we saw all the components of a Traceback message. I’ll summarize it in the following points:

  • It’s called a Traceback message as you can use it to trace it back to the point where the error is in your code
  • The StackTrace part shows where the error occurred in a program down to the exact line
  • The Exception Name tells us the error type
  • The Excpetion Message is a short message briefly describing the error
  • Reading the Traceback from bottom to top is more efficient to understand what went wrong and where!

And that’s a wrap people!

Congratulations on reading till the end of the article, not many people have the focus and perseverance to do so!

Here are some more articles to help you on your journey to become a Python craftsman!

Related articles

Python: Catch Exception and Print

Python: Print Just the Message of Exception

Python: Print StackTrace on Exception!

Python: Print Exception Type

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



Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn