You can raise an error deliberately when your function is given something it cannot work with. This is not rudeness, it is a contract: the function states what it needs and refuses to produce a wrong answer quietly.
Raising deliberately
PYTHON
def average(numbers):
if len(numbers) == 0:
raise ValueError("Cannot average an empty list")
return sum(numbers) / len(numbers)
≈
JAVASCRIPT
function average(numbers) {
if (numbers.length === 0) {
throw new Error("Cannot average an empty list");
}
return numbers.reduce((a, b) => a + b, 0) / numbers.length;
}
Compare → Python says raise, JavaScript says throw. Same concept, different keyword. Both stop the function immediately and hand the problem to whoever called it.
EXAMPLE
loading editor…
YOUR TURN
Your turn → Write a function check_age(age) that raises a ValueError for a negative age, then call it with -3 inside a try and print the message.
loading editor…
Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.
finally runs no matter what happens, whether the code succeeded, failed, or returned early. It is where cleanup belongs.
EXAMPLE
loading editor…
YOUR TURN
Your turn → Add a third call, risky(5), and check where each "checked" line appears in the output.
loading editor…
Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.
◈ Graded Challenge
Write a function that divides the first number by the second and returns the result rounded to two decimal places. If the second number is zero, it must return the string "undefined" instead of crashing. Do not let any error escape the function.
Name it exactly: def safe_divide(a, b):
3 visible + 2 hidden
loading editor…
Mark this lesson complete
Signed in, your progress follows you to every device.