The Message of an Error
Every exception carries a message: the text after the colon on the last line of a traceback, such as invalid literal for int() with base 10: 'two'. When you catch an exception, you can get the message too. Write as and a name after the type:
text = "two"
try:
number = int(text)
except ValueError as error:
print("Something went wrong:", error)Something went wrong: invalid literal for int() with base 10: 'two'except ValueError as error: catches a ValueError as before, and it also stores the exception in the variable error. You choose the name; in other people's code, you'll often see e or err. When you print the exception, or put it in an f-string, you get its message. Use the variable only inside the except block: when the block ends, Python deletes it.
Each type of exception has messages of its own. A KeyError's message is just the key that is missing, in quotes:
menu = {"coffee": 3, "tea": 2}
try:
print(menu["juice"])
except KeyError as error:
print("Missing key:", error)Missing key: 'juice'as works with a tuple too: except (ValueError, KeyError) as error: catches both types, and error holds whichever of them happened. That's where the message is most useful: the same block prints a different message for each problem, so you can see what went wrong.
Python's messages are written for programmers. Print them where a programmer will read them, for example in a list of what a program couldn't process. For the people who fill in your form, a message of your own, like Please enter a number., is friendlier. Later in this lesson, you'll learn to raise exceptions with messages of your own.
Instructions
- 1
The second bill is for 0 people, so the program ends with a
ZeroDivisionError, and the third one would end it with aValueError. Put the calculation and theprint()into atryblock, with oneexceptthat catches both types and stores the exception inerror. It printsCan't split this bill:and the message. The output should be:Each pays $9.00 Can't split this bill: division by zero Can't split this bill: invalid literal for int() with base 10: 'five' Each pays $10.00 - 2
The bills that couldn't be split have to be checked by hand. Count them: after the loop, print
Bills to check: 2.