raise and Validation

Exception Handling

raise and Validation

In this tutorial, we'll create clear errors when values are not acceptable.

Sometimes your code should create an exception on purpose. Use raise.

raise ValueError("Age cannot be negative")

This stops the program unless the exception is handled.

Why Raise Errors?

Raising errors is useful when a value is not acceptable.

def require_positive(number):
    if number <= 0:
        raise ValueError("Number must be positive")
    return number

The function clearly rejects invalid input.

Validation in Functions

Validation means checking that data is acceptable before using it.

def divide(a, b):
    if b == 0:
        raise ValueError("b cannot be zero")
    return a / b

This gives a clear error message before Python reaches a less friendly division error.

Handling a Raised Error

You can catch errors raised by your own functions:

try:
    result = divide(10, 0)
except ValueError as error:
    print(error)

Output:

b cannot be zero

as error stores the exception message so you can print it.

Common Mistake

Do not use exceptions for normal decisions that are easy to check:

if age >= 18:
    print("Adult")
else:
    print("Child")

That does not need an exception. Exceptions are for problems or invalid situations.

Practice

Create a function called set_password(password). If the password is shorter than 8 characters, raise a ValueError. Otherwise return "Password accepted".