Dividing By Zero
00:00
In the previous lesson, I showed you how to write your own exception. In this lesson, I’m going to dive a little deeper into the attributes of the Exception
class.
00:10
The Exception
object has a few parts that may be of use to you. The .args
attribute, which you saw in an earlier lesson, contains the objects passed into the constructor, which is typically the error message, but it can have other things as well.
00:25
Python 3.11 introduced the add_note()
function that allows you to add more information to an exception. This can be helpful when handling someone else’s exceptions.
00:35
Consider some code where you were using a third-party library that raised an exception. You could call add_note()
and add more information to that exception to let your user or programmers know just what caused the problem.
00:49 And as everything in Python is an object, even the traceback info that I was talking about earlier is an object. The traceback object contains the stack information about how you got to this exception.
01:02
And inside the exception, it’s stored on an attribute called .__traceback__
, also known as dunder traceback. Alright, off to the REPL let’s go play with these.
01:15
I’m gonna divide by zero inside this try
block. And of course, that’s gonna raise an exception.
01:23
This handling block handles all exceptions, which of course includes the zero division error. The use of the as
keyword here allows me to put the contents of the exception that was triggered into a variable whose scope is the Exception
block itself. Inside the block,
01:45
the first thing I do is add some information by calling the add_note()
function to the Exception
object, passing in a new message.
01:54
Since the error is only in scope in the except
block, if I want to use it outside, I need to put it in a separate variable.
02:04
And finally, I’m gonna store the .__traceback__
in its own variable as well.
02:12 As the exception handling block doesn’t print anything, there was nothing to see here. An exception fired, it got handled and the REPL returned. But now my error is populated. Let’s take a look at it.
02:26
Not surprisingly, it’s a ZeroDivisionError
.
02:33
The .__notes__
attribute contains the note I added. You can call add_note()
multiple times, which is why .__notes__
is a list and the traceback object is, well, a traceback object. Debuggers use the info inside of it to show you the call stack.
02:49 But all I’m gonna do is tell you that it’s there. Anything deeper is out of scope for this course.
Become a Member to join the conversation.