PY-101 ยท Files and errors
Raising and custom exceptions
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
raise stops a function and signals a problem, such as raise ValueError("amount must be positive"). A custom exception is a small class that inherits from Exception, which lets callers catch your specific problem by name. Raising early with a clear message makes bugs obvious.
- Raise built-in exceptions with a message
- Create a custom exception class
- Catch it by name
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
class InsufficientFunds(Exception):passdef withdraw(balance, amount):if amount <= 0:raise ValueError(f"amount must be positive, got {amount}")if amount > balance:raise InsufficientFunds(f"balance {balance} is less than {amount}")return balance - amountprint(withdraw(2000, 500))for amount in (5000, -50):try:withdraw(2000, amount)except InsufficientFunds as e:print("Refused:", e)except ValueError as e:print("Invalid:", e)
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
1500
Refused: balance 2000 is less than 5000
Invalid: amount must be positive, got -50 ๐ฏ Make set_age(age) raise ValueError when age is below 0 or above 150, and return age otherwise. set_age(30) should print 30.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
if age < 0 or age > 150: raise ValueError("age must be 0-150")
- The problemA banking function is asked to withdraw โน5,000 from an account holding โน2,000. Silently returning a negative balance would be a disaster. Raising an error stops it at once.
- The Python idea
class MyError(Exception):raise stops a function and signals a problem, such as raise ValueError("amount must be positive"). - In real lifeWeb frameworks define exceptions like NotFound and PermissionDenied; raising one anywhere turns into the right error page.
Start with a question
A banking function is asked to withdraw โน5,000 from an account holding โน2,000. Silently returning a negative balance would be a disaster. Raising an error stops it at once.
Good libraries fail loudly with clear errors. That is how you catch mistakes in testing instead of in production.
Explain it like I'm 10
raise is pulling the emergency cord on a train: everything stops and everyone hears why.
The technical explanation
raise ValueError("message") creates the error and stops the function immediately.
class InsufficientFunds(Exception): pass defines a new kind of error.
Callers can except InsufficientFunds: to handle exactly that case and let others pass.
Syntax
class MyError(Exception):
pass
raise MyError("what went wrong") Real-world scenario
Web frameworks define exceptions like NotFound and PermissionDenied; raising one anywhere turns into the right error page.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: import and from โQuestions people ask
How do I create a custom exception in Python?
Define a class that inherits from Exception: class PaymentFailed(Exception): pass. Raise it with raise PaymentFailed("reason").
Should I raise or return an error value?
Raise. Error values are easy to ignore by accident; exceptions stop the program unless someone deliberately handles them.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner How do I create a custom exception in Python?
Define a class that inherits from Exception: class PaymentFailed(Exception): pass. Raise it with raise PaymentFailed("reason").
beginner Should I raise or return an error value?
Raise. Error values are easy to ignore by accident; exceptions stop the program unless someone deliberately handles them.
intermediate What does raise do?
Signals an error and stops the function. It raises an exception.
intermediate A custom exception should inherit from?
Exception. Inherit from Exception.
Quick revision
Remember
- Raise built-in exceptions with a message
- Create a custom exception class
- Catch it by name
- Raise with a helpful message that says what went wrong and what was expected: "amount must be positive, got -50".
Syntax
class MyError(Exception):
pass
raise MyError("what went wrong") Official documentation
- Raising exceptions (docs.python.org)
- User-defined exceptions (docs.python.org)