CodingNic

Error Handling and Debugging

Raise

Error Handling and Debugging 24 min read

Raise

Raise

Sometimes Python creates errors for you.

But sometimes you should create an error when data is wrong.

Python gives us raise for this.

What Is raise?

raise lets you stop the program and create an exception manually.

You use it when something should not be allowed.

Why raise Matters

It helps you:

  • Validate data
  • Stop bad input
  • Protect your program
  • Show clear error messages

Basic Structure

python
raise ErrorType("message")

Example: Negative Age

python
age = -5

if age < 0:
    raise ValueError("Age cannot be negative")

Result

Python shows an error message because the value is not allowed.

Example: Password Too Short

python
password = "123"

if len(password) < 6:
    raise ValueError("Password too short")

Example: Use raise with try

python
try:
    score = int(input("Enter score: "))

    if score < 0 or score > 100:
        raise ValueError("Score must be between 0 and 100")

    print("Valid score")

except ValueError as error:
    print(error)

Example Output

text
Enter score: 120
Score must be between 0 and 100

Common Error Types to Raise

  • ValueError
  • TypeError
  • ZeroDivisionError
  • Exception

Usually ValueError is great for bad user input.

Why Not Only Use if?

An if can check rules.

raise adds a real error that can be caught and handled.

This is useful in larger programs and functions.

Example: Function Validation

python
def set_price(price):
    if price < 0:
        raise ValueError("Price cannot be negative")

    print("Saved")

set_price(10)

Output

text
Saved

Code Along

Build a username checker.

Rules:

  • Name cannot be empty
  • If empty, raise an error

Mini Challenge

Build a ticket checker.

Steps:

  • Ask for age
  • Convert to number
  • If age is below 0, raise an error
  • If age is valid, print:
text
Ticket allowed
  • Handle the error with try/except

Expected output:

text
Enter age: -1
Age cannot be negative

Real World Use Case

Programs use raise in forms, payments, APIs, login systems, and business rules.

Quiz

  1. What does raise do?
  2. Why use raise?
  3. Which error type is common for bad input?
  4. Can raised errors be caught with try/except?

Assignment

Create a function that accepts a number. Raise an error if the number is less than 1.

Summary

You learned how to create your own errors using raise to protect your program and validate data.