Try/Except/Raise Examples

Published: 24 January 2018
on channel: Matt Haberland
157
0

Note: regarding the
"DeprecationWarning: BaseException.message has been deprecated as of Python 2.6"
(See: https://stackoverflow.com/questions/1...)

This means that you're not supposed to access the `message` of an exception object directly, like:
if e.message.startswith....

Apparently - and I was woefully out of date on this - starting in Python 3 the initializer of the `BaseException` class (of which `TypeError` is a subclass / derived class) no longer stores the first argument passed into it in an instance variable called `message`.

The first argument of exception initializers is still used in a similar way - it is supposed to be a message about went wrong, so:
TypeError("argument 2 to map() must support iteration")
is just fine.

But you can't access that string by looking at a `message` instance variable /attribute anymore. No message attribute exists. The string is stored somewhere else.

However, based on:
https://stackoverflow.com/questions/3...
It looks like exception classes will work have a `__str__` function. So we could have changed our logic to:
if str(e).startwsith...

Ideally, we probably shouldn't be relying on that string to tell us what went wrong, as the specific wording of the string could change in future versions of Python. Maybe we should include an additional test to determine which sort of TypeError occurred rather than relying on the message, but that would involve a nested try/except and that doesn't look great to me either. In any case, for now, I think this illustrated the basic points I was trying to convey about how exceptions might be used "in the wild", that is, less contrived examples.


On this page of the site you can watch the video online Try/Except/Raise Examples with a duration of hours minute second in good quality, which was uploaded by the user Matt Haberland 24 January 2018, share the link with friends and acquaintances, this video has already been watched 157 times on youtube and it was liked by 0 viewers. Enjoy your viewing!