← Back to Blog

Throw your own errors

The problem...

Python raises errors when something goes wrong — wrong type, wrong value, division by zero.

But sometimes you need to raise an error yourself. The input is technically valid — but it makes no sense for your program.

Age of -5. BMI of 0. A username that's one character long.

Python won't catch these. You have to.

The idea!

raise lets you throw an error deliberately. You decide the condition. You decide the message. Your function enforces its own rules.

The syntax

raise ErrorType("Your message here")

Your first raise

def get_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative.")
    return age

try:
    print(get_age(-5))
except ValueError as e:
    print(e)    # Age cannot be negative.

raise stops the function immediately and throws the error. except catches it — and as e gives you access to the message.

Validating input in a function

def calculate_bmi(weight, height):
    if weight <= 0:
        raise ValueError("Weight must be greater than zero.")
    if height <= 0:
        raise ValueError("Height must be greater than zero.")
    return weight / height ** 2

try:
    bmi = calculate_bmi(70, 0)
except ValueError as e:
    print(e)    # Height must be greater than zero.

The function enforces its own rules before doing any calculation. Bad input never reaches the formula.

raise inside a loop

def get_positive_number():
    while True:
        try:
            number = int(input("Enter a positive number: "))
            if number <= 0:
                raise ValueError("Must be positive.")
            return number
        except ValueError as e:
            print(e)

The loop keeps asking. Every bad value — whether wrong type or negative — is caught and reported. Only a valid positive number gets through.

Heads up!

  • raise stops the function immediately — like return, but with an error
  • Use ValueError for wrong values, TypeError for wrong types
  • as e gives you access to the error message — print(e)
  • Always catch raised errors with try / except — or the program crashes

The mindset shift

Stop thinking: "Python will catch bad input."

Start thinking: "My function has rules. If they're broken — I raise the error."

What you should understand now

  • raise ErrorType("message") — throw an error deliberately
  • Use it to enforce rules your function can't rely on Python to catch
  • as e in except — access the error message
  • Always pair raise with try / except — or the program crashes
[ login to bookmark ] // copied! 20 views · 1 min
// resources
Code Example raise_statement.py
← prev There's more to error handling than catching next → ErrorHandling Mini Project — BMI Calculator
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.