Lesson 40 of 60
โฎPrev Nextโฏ

PY-101 ยท Files and errors

Raising and custom exceptions

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

40of 60

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก 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.

    Raising and custom exceptions, running
    1. class InsufficientFunds(Exception):
    2. pass
    3. def withdraw(balance, amount):
    4. if amount <= 0:
    5. raise ValueError(f"amount must be positive, got {amount}")
    6. if amount > balance:
    7. raise InsufficientFunds(f"balance {balance} is less than {amount}")
    8. return balance - amount
    9. print(withdraw(2000, 500))
    10. for amount in (5000, -50):
    11. try:
    12. withdraw(2000, amount)
    13. except InsufficientFunds as e:
    14. print("Refused:", e)
    15. except ValueError as e:
    16. print("Invalid:", e)
    Press โ–ถ to watch Python run this, one line at a time.
    1. 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.
    2. The Python ideaclass MyError(Exception):raise stops a function and signals a problem, such as raise ValueError("amount must be positive").
    3. 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")

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    Real-world scenario

    Web frameworks define exceptions like NotFound and PermissionDenied; raising one anywhere turns into the right error page.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. What does raise do?
    2. 2. A custom exception should inherit from?
    3. 3. Why create custom exceptions?
    4. 4. What is a good error message?
    5. 5. After raise inside a function, does the next line run?

    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