Course 2.1Lesson 4 of 5
Your own code can raise an error with raise, for example raise ValueError with a clear message, when a function gets a value that it cannot use. A function that checks its input and raises a clear error is easier to use than one that fails later with a confusing message. The caller can catch the error with try and except and read the message. An error that nobody catches stops the program with your message. There are two styles of care: look before you leap, which checks first with an if, and try and catch, which uses the error. Choose the first when a simple check exists, and the second when the check is hard, as for a number in text.
Try the code and the simulations beside the lesson.
After this lesson you can
So far, Python raised the errors. But your own functions can raise errors too, with the word raise. Why would you want to?
Imagine a function set_age(age). If someone calls it with -5 or with the text "ten", what should it do? It could carry on and store a nonsense age. Then, much later, a different part of the program fails in a way that has nothing to do with the real cause. This is the worst case. It is much better to refuse at the door, at once, with a message that says what is wrong.
Choose the kind with care, as Python does: a value of the right type but a bad content is a ValueError. A value of the wrong type is a TypeError.
Is that bad? No, it is the right thing in many cases. A program that goes on with a wrong value is worse than one that stops and says why. A good message makes it easy for the next programmer, perhaps you, to fix the call.
A good message says what was wrong, and what was expected.
raise ValueError("bad").raise ValueError("age must be from 0 to 120, not 200").It names the rule, and shows the bad value.
The function does not print or ask again. It raises the error, and the caller, which knows the situation, handles it.
There are two ways to deal with a risk. People call them "look before you leap" and "easier to ask forgiveness than permission". Here they are with a dictionary.
A rough guide: if one short if does the check, use it. If the check is as hard as the job itself (a number in text, a file that may not exist), try and catch.
0 or None may be better."error" or "bad".ValueError for a bad content, TypeError for a bad type.except:. Name the kind.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
raise ValueError("message") makes an error of your own, and stops the function at once.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
-5?"ten"?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.