Ravindra BagaleCourses & study guides मराठी Track your progress

Python Errors and Exceptions: How to Use try, except, else and finally

P8.5 How to Raise an Error in Python for Bad Data

Why. Sometimes the data is technically valid but wrong for the business: a negative quantity, an age of 250. Stop early with a clear message.

What. raise ValueError("message") creates an error on purpose.

How.

Validate input

  1. Check the value with if.
  2. If it is wrong, raise an error with a clear message.
  3. Callers can catch it with try/except.

Worked example A — Reject a negative quantity.

Step 1 — What we do. An order system for a warehouse in Hamburg.

Step 2 — Type and run this code.

def check_qty(q):
    if q < 0:
        raise ValueError(f"Quantity cannot be negative: {q}")
    return q

print(check_qty(5))
check_qty(-2)

Step 3 — Output you should see.

5
ValueError: Quantity cannot be negative: -2

Step 4 — What it means. The first call passes. The second stops with our own clear message.

Worked example B — Catch your own error.

Step 1 — What we do. We validate a list of ages from a clinic and collect problems.

Step 2 — Type and run this code.

def check_age(a):
    if not 0 <= a <= 120:
        raise ValueError(f"Bad age: {a}")
    return a

problems = []
for a in [34, 250, 61, -1]:
    try:
        check_age(a)
    except ValueError as e:
        problems.append(str(e))
print(problems)

Step 3 — Output you should see.

['Bad age: 250', 'Bad age: -1']

Step 4 — What it means. as e gives the error object; str(e) is its message. Now you have a data quality report.

Ravindra Bagale's Tip

Fail loudly on impossible values. A silent wrong number in a report is worse than a clear error.

Samajla ka? If yes, take the quiz for this chapter. If not, run every example again and change one value each time.