Concept
Raising Errors Manually with `raise`
Trigger your own exception deliberately using `raise ExceptionType("Error explanation")` when input violates business rules.
python
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")
return f"Valid age: {age}"
print(check_age(25))
# 113. Raising Errors Manually with `raise` Trigger your own exception deliberately using `raise ExceptionType("Error explanation")` when input violates business rules: ```python def check_age(age): if age < 0: raise ValueError("Age cannot be negative!") return f"Valid age: {age}" print(check_age(25)) ``` Unlike JavaScript or Java which use `throw`, Python uses `raise`. Raising exceptions halts corrupted operations before invalid data enters your database.
Checkpoint
What keyword triggers an intentional exception in Python?
Practice
Write a function `withdraw(amount)` that raises a `ValueError("Negative amount")` if `amount < 0`, or returns `amount`. Catch the error for `-50` and print `"Caught error"`.
01
Tap code blocks below to assemble
Available Blocks