Chapter 44 of 54

Exception Handling in Python

No matter how careful you are, things go wrong while a program runs. A user types "abc" when you asked for a number, a file you want to open does not exist, or you accidentally divide by zero. When this happens, Python stops your program and prints an error.

Exception handling lets you catch these errors and decide what to do instead of letting the program crash. It is what separates a fragile script from a reliable program.

What is an Exception?

An exception is an error that happens while the program is running. If it is not handled, Python stops the program and shows a traceback.

print("Start")
print(10 / 0)
print("End")

Output:

Start
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(10 / 0)
          ~~~^~~
ZeroDivisionError: division by zero

Notice that "End" never prints. The program stopped at line 2. Read a traceback from the bottom up: the last line tells you the exception type (ZeroDivisionError) and the message (division by zero), and the lines above show where it happened.

Errors vs exceptions

A syntax error (like a missing colon) is found before the program even starts, so it cannot be caught. An exception happens while the code runs, and that is what we can handle.


Common Built-in Exceptions

ExceptionWhen it happensExample
ZeroDivisionErrorDividing by zero10 / 0
ValueErrorRight type, wrong valueint("abc")
TypeErrorWrong type for an operation"5" + 5
IndexErrorList index out of range[1, 2][5]
KeyErrorMissing dictionary key{"a": 1}["b"]
NameErrorUsing an undefined variableprint(xyz)
AttributeErrorObject has no such attribute"hi".push()
FileNotFoundErrorOpening a file that does not existopen("missing.txt")
ModuleNotFoundErrorImporting a module that is not installedimport notreal

The try and except Block

Put the risky code inside try. If an exception happens, Python jumps to the matching except block instead of crashing.

try:
    print(10 / 0)
except ZeroDivisionError:
    print("You can't divide by zero!")

print("Program continues")

Output:

You can't divide by zero!
Program continues

How it works step by step:

  1. Python runs the code inside try line by line.

  2. If no exception occurs, the except block is skipped completely.

  3. If an exception occurs, the rest of the try block is skipped and Python looks for an except that matches the exception type.

  4. If a match is found, that block runs and the program continues after the whole try statement. If no match is found, the program crashes as usual.


Handling Multiple Exceptions

Separate except blocks

Different errors often need different messages:

def convert(value):
    try:
        number = int(value)
        print("Converted:", number)
    except ValueError:
        print(f"'{value}' is not a valid number")
    except TypeError:
        print(f"Cannot convert {type(value).__name__} to int")

convert("42")
convert("abc")
convert(None)

Output:

Converted: 42
'abc' is not a valid number
Cannot convert NoneType to int

Python checks the except blocks from top to bottom and runs only the first one that matches.

One block for several exceptions

If you want the same handling for several types, group them in a tuple:

for v in ["5", "x", [1]]:
    try:
        n = int(v)
        print("Got", n)
    except (ValueError, TypeError) as e:
        print("Error:", e)

Output:

Got 5
Error: invalid literal for int() with base 10: 'x'
Error: int() argument must be a string, a bytes-like object or a real number, not 'list'

Getting the error message with as

except SomeError as e stores the exception object in e. Printing it gives the message:

try:
    nums = [1, 2, 3]
    print(nums[5])
except IndexError as e:
    print("Error:", e)
    print("Type:", type(e).__name__)

Output:

Error: list index out of range
Type: IndexError

else and finally

A try statement can have two more optional parts:

  • else runs only if no exception happened in try.

  • finally runs always, whether there was an exception or not. It is used for clean-up work like closing files or connections.

def divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("Cannot divide by zero")
    else:
        print("Result:", result)
    finally:
        print("Done")

divide(10, 2)
divide(5, 0)

Output:

Result: 5.0
Done
Cannot divide by zero
Done

The flow looks like this:

          try
         /    \
  no error     error
      |          |
    else       except
       \        /
        finally
           |
     rest of program

Why use else instead of putting the code in try? It keeps the try block small, so you only catch errors from the line you actually expect to fail.

finally runs even when the try block uses return:

def test():
    try:
        return "from try"
    finally:
        print("finally runs before returning")

print(test())

Output:

finally runs before returning
from try

Raising Exceptions with raise

You can trigger an exception yourself when your function receives invalid data. This is better than silently continuing with wrong values.

def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    print("Age set to", age)

try:
    set_age(21)
    set_age(-5)
except ValueError as e:
    print("Error:", e)

Output:

Age set to 21
Error: Age cannot be negative

Re-raising an exception

Sometimes you want to do something (like logging) and then let the error continue upward. A bare raise inside an except block re-raises the same exception:

def load():
    try:
        return int("abc")
    except ValueError:
        print("Logging the problem...")
        raise

try:
    load()
except ValueError as e:
    print("Caught again:", e)

Output:

Logging the problem...
Caught again: invalid literal for int() with base 10: 'abc'

Custom Exceptions

For your own programs, you can create exception types with meaningful names. A custom exception is a class that inherits from Exception. You will learn classes and inheritance properly in later chapters; for now, just copy this pattern:

class InsufficientBalanceError(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientBalanceError(f"Need {amount}, but only {balance} available")
    return balance - amount

try:
    print(withdraw(1000, 300))
    print(withdraw(1000, 5000))
except InsufficientBalanceError as e:
    print("Transaction failed:", e)

Output:

700
Transaction failed: Need 5000, but only 1000 available

A name like InsufficientBalanceError tells the reader exactly what went wrong, which a generic ValueError cannot.


The Exception Hierarchy

Exceptions are organised in a family tree. Catching a parent also catches all of its children.

BaseException
├── KeyboardInterrupt      (Ctrl + C)
├── SystemExit             (sys.exit())
└── Exception              (almost everything else)
    ├── ArithmeticError
    │   └── ZeroDivisionError
    ├── LookupError
    │   ├── IndexError
    │   └── KeyError
    ├── OSError
    │   └── FileNotFoundError
    ├── TypeError
    └── ValueError

So except LookupError catches both IndexError and KeyError. This is also why the order of except blocks matters: put specific exceptions first and general ones last, or the specific block will never run.


A Practical Example: Safe Number Input

A classic use of exception handling is asking the user again until they enter valid data:

while True:
    text = input("Enter your age: ")
    try:
        age = int(text)
        if age < 0:
            raise ValueError("age cannot be negative")
    except ValueError as e:
        print("Invalid input:", e)
    else:
        print("Your age is", age)
        break

Sample run:

Enter your age: abc
Invalid input: invalid literal for int() with base 10: 'abc'
Enter your age: -3
Invalid input: age cannot be negative
Enter your age: 25
Your age is 25

Common Mistakes

  • Using a bare except:. It catches everything, including KeyboardInterrupt (so Ctrl + C stops working) and your own typos like NameError. Always name the exception you expect.

  • Catching Exception and ignoring it. Writing except Exception: pass hides bugs. If you catch broadly, at least print or log the error.

  • Putting too much code inside try. Keep only the line that can fail inside it; move the rest to else.

  • Wrong order of except blocks. except Exception before except ValueError means the ValueError block can never run.

  • Using exceptions where a simple check is clearer. For a dictionary, marks.get("Ravi", "Not found") is often simpler than catching KeyError.


Summary

KeywordPurpose
tryWraps code that might fail
exceptHandles a specific exception
elseRuns if no exception occurred
finallyAlways runs (clean-up)
raiseTriggers an exception yourself

Catch only the exceptions you expect, handle them meaningfully, and let unexpected errors surface so you can fix them.

Interview tip: A common question is "What is the difference between else and finally?" Answer: else runs only when the try block succeeds; finally runs every time, even if there is an exception or a return.

In the next chapter, you will use exception handling right away while working with files, where errors like FileNotFoundError are very common.