Python 3D Academyবাংলা

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 yourself
  • ValueError("..."): the right kind of value, but a bad one, like a negative age
  • TypeError("..."): 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):

  1. The check age < 0 is True.
  2. raise ValueError("age can't be negative") stops the function; return age never runs.
  3. 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" gives TypeError: 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

  1. 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)
  2. Which error fits a function that gets a negative number of tickets?

    • ValueError
    • NameError
    • IndexError
  3. What does this print?

    try:
        raise ValueError("bad input")
    except ValueError as e:
        print(e)
  4. 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)
  5. Which line has a mistake?

    def set_speed(speed):
        if speed < 0:
            return ValueError("negative speed")
        return speed
    
    print(set_speed(-5))

Coding tasks

  1. Write check_age(age) that returns age if it is from 0 to 150, and raises a ValueError otherwise.

  2. Write withdraw(balance, amount) that returns the new balance. Raise a ValueError if amount is 0 or less, or more than the balance.

  3. Write average(nums) that returns the average of a list, and raises a ValueError for an empty list (instead of a ZeroDivisionError).