← Back to Python Course | Chapter 10: Exception Handling | Lesson 1 of 5

Python Exception Handling

An exception is what happens when something goes wrong while a program runs, like tripping over a rock on a walk. Handling exceptions means planning what to do instead of falling over.
Syntax
python
try:
    # code that may raise an error
except ExceptionType:
    # handle the error

What is an Exception?

An exception is an error Python detects while your program is running (as opposed to a syntax error caught before it even starts) -- if nothing handles it, the exception propagates up and crashes the program with a traceback, which is why handling matters for code that shouldn't just stop unexpectedly.

Example: What is an Exception?

python
try:
    print(1 / 0)  # raises ZeroDivisionError at runtime
except ZeroDivisionError:
    print("Caught an exception instead of crashing")

Built-in Exceptions

Python ships with many specific built-in exception types -- ZeroDivisionError, TypeError, ValueError, and more -- and catching the specific type you expect (rather than a bare except) makes your error handling precise instead of accidentally swallowing unrelated bugs.

Example: Built-in Exceptions

python
try:
    int("abc")
except ValueError:  # catches only this specific error type
    print("Caught a specific ValueError")

Raising Exceptions

The raise keyword lets your own code deliberately trigger an exception, which is how you signal 'this input is invalid' from deep inside a function -- raise ValueError('age must be positive') stops execution there and lets a caller's except block decide how to respond.

Example: Raising Exceptions

python
def set_age(age):
    if age < 0:
        raise ValueError("age must be positive")  # deliberately triggers an exception
    return age

try:
    set_age(-5)
except ValueError as e:
    print(e)

Creating Custom Exceptions

Subclassing the built-in Exception class lets you create your own exception types specific to your application's domain (like InsufficientFundsError), which makes error handling code more readable than checking for generic exceptions and guessing what actually went wrong.

Example: Creating Custom Exceptions

python
class InsufficientFundsError(Exception):  # custom exception type for this domain
    pass

try:
    raise InsufficientFundsError("Not enough balance")
except InsufficientFundsError as e:
    print(e)

Exception Hierarchy

Every built-in exception ultimately inherits from the base Exception class, so an except Exception: block will catch essentially any error your code raises -- but catching that broadly is usually too blunt for production code, since it also hides bugs you'd want to know about.

Example: Exception Hierarchy

python
try:
    int("abc")
except Exception as e:  # catches virtually any error, since all inherit from Exception
    print("Caught by the base Exception class:", type(e).__name__)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Reading an error message only for its last line, when the traceback shows where the problem started.
  2. Raising a string, as in raise "error", which is a TypeError; raise an exception instance such as ValueError("bad").
  3. Using exceptions for normal flow control, when a simple if check would be clearer.
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.