Python 3.11: A Guided Tour Through Code Transcripts
Chapter: Error Messages
Lecture: PEP 678: Enriching Exceptions with Notes
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
The previous feature we saw that when python fully crashes or you somehow gather up a trace back their ways.
0:09
You can take an exception and extract the trace back and print it.
0:13
For example you get better messages. But sometimes in the normal flow of your program you just want to catch
0:22
an exception and see a message. Sometimes that message is helpful.
0:26
Other times it's not enough information. So that brings us to PEP 678 enriching exceptions with notes done by Zac
0:37
Hatfield Dodds, sponsored by Irit Katriel. This is a way to catch an exception.
0:43
Potentially temporarily add some more context that you might have about this error and then let it be raised further up
0:50
the call stack where it's meant to be handled. Or even when you're throwing the exception,
0:55
you can add more details about what went wrong and why in this new notes list that is associated with all
1:03
exceptions. Let's see an example here we have a function called setup app. We're going to call it and we get a database connection exception.
1:16
It gives us a nice message. The connection string is malformed. Well that's not super helpful. What way is it malformed?
1:25
Is there anything else you could tell me about it notice we're calling, we call set up app, it calls connect to db passing a connection string.
1:34
A server in support. Well it must have come up with this connection string and somehow done it wrong.
1:40
I don't know but here's the exception. Not terribly helpful.
1:45
However, with this new feature we just introduced, we can call the same code and if setup app is
1:52
a little helpful and it says, you know, in this situation here's what's actually going wrong.
1:57
And then let's set exception keep going. We'll get something more like this. Same error. Connection strings malformed. But check out those notes.
2:05
Note, you cannot specify the server. Report in both the connection string and explicitly.
2:11
So here we're calling connected database by passing a server in support presumably.
2:16
But maybe in the connection string it says something like Mongodb:// server colon ports/database.
2:24
And then we're also passing the server and maybe those values are in conflict they're different or something like that.
2:30
So we get this extra information. You cannot specify the server import in both the connection string and explicitly.
2:36
That is helpful. And then we even get some more encouraging advice here, amend the connection string. Try again. So that's what this feature is about.