Raising your own errors
🌍 In real life. A bank teller asked to withdraw 80 taka from an account holding 50 doesn't hand over 50 and say nothing; she stops and says clearly, "not enough money". A clear refusal is far better than a quiet wrong answer that someone discovers weeks later.
Your functions can refuse like that too, with raise.
The idea in one sentence: raise ValueError("message") stops a function on purpose when it gets a value it can't work with, and the error travels to whoever called it.
Its words:
raise: start an error yourselfValueError("..."): the right kind of value, but a bad one, like a negative ageTypeError("..."): the wrong kind of value, like text where a number was needed- the message: the text in brackets, which appears in the traceback's last line
Step by step, for set_age(-4):
- The check
age < 0is True. raise ValueError("age can't be negative")stops the function;return agenever runs.- The caller's
except ValueError as e:catches it and prints the message.
def set_age(age):
if age < 0:
raise ValueError("age can't be negative")
return age
print(set_age(12))
try:
set_age(-4)
except ValueError as e:
print("Refused:", e)If nobody catches it, a raised error stops the program just like Python's own errors, with your message in the last line:
def withdraw(balance, amount):
if amount > balance:
raise ValueError("not enough money")
return balance - amount
print(withdraw(50, 20))
print(withdraw(50, 80))Why raise instead of returning something odd? If withdraw returned -30 or None for a bad request, the caller might not notice and carry on with a wrong balance. An error can't be ignored by accident: either someone handles it on purpose, or the program stops right where the problem is, with your clear message.
Mistakes and edge cases.
- Raising a plain string.
raise "oops"givesTypeError: exceptions must derive from BaseException. Raise an error type:raise ValueError("oops"). - A vague message. "error" tells nobody anything; say what was wrong, like "not enough money".
- Checking too late. Raise before changing anything, so a refused call leaves things as they were.
- Catching your own error inside the same function. Then it never reaches the caller; let the caller decide what to do.
Quiz
What does this print?
def check(n): if n > 10: raise ValueError("too big") return n try: print(check(3)) print(check(30)) except ValueError as e: print("Error:", e)Which error fits a function that gets a negative number of tickets?
- ValueError
- NameError
- IndexError
What does this print?
try: raise ValueError("bad input") except ValueError as e: print(e)What does this print?
def half(n): if n % 2 != 0: raise ValueError("odd") return n // 2 results = [] for n in [4, 7, 10]: try: results.append(half(n)) except ValueError: results.append("odd") print(results)Which line has a mistake?
def set_speed(speed): if speed < 0: return ValueError("negative speed") return speed print(set_speed(-5))
Coding tasks
Write
check_age(age)that returns age if it is from 0 to 150, and raises aValueErrorotherwise.Write
withdraw(balance, amount)that returns the new balance. Raise aValueErrorif amount is 0 or less, or more than the balance.Write
average(nums)that returns the average of a list, and raises aValueErrorfor an empty list (instead of a ZeroDivisionError).