agyanadda@gmail.com

Python Exception Handling

Files and Exceptions 1 min read Updated Dec 4, 2026 Topic 22 of 32

An exception is an error that happens while the program runs. Unhandled, it stops the program with a traceback.

Common exceptions

ValueError, TypeError, ZeroDivisionError, KeyError, IndexError, FileNotFoundError, AttributeError, ImportError.

try / except

try:
    risky code
except ValueError:
    handle it
except (KeyError, IndexError) as e:
    print(e)
else:
    runs if no error
finally:
    always runs (cleanup)

Catch specific exceptions. A bare except: hides real bugs.

raise

raise ValueError("Age cannot be negative") — signal a problem yourself. Inside except, a bare raise re-raises the same error.

Custom exceptions

class InsufficientBalance(Exception): pass — clear names for your app's errors.

Exception chaining

raise PaymentError("Payment failed") from err keeps the original cause.

Use logging.exception() inside except to log the full traceback.

Example

Example — Safe input and a bank account Python
class InsufficientBalance(Exception):
    pass

def withdraw(balance, amount):
    if amount <= 0:
        raise ValueError("Amount must be positive")
    if amount > balance:
        raise InsufficientBalance(f"Balance {balance} is less than {amount}")
    return balance - amount

for attempt in ["abc", "-50", "5000", "300"]:
    try:
        amount = int(attempt)
        balance = withdraw(1000, amount)
    except ValueError as e:
        print(f"{attempt!r}: invalid -> {e}")
    except InsufficientBalance as e:
        print(f"{attempt!r}: {e}")
    else:
        print(f"{attempt!r}: success, new balance {balance}")
    finally:
        print("  (transaction checked)")

'abc' gives an invalid literal error, '-50' gives Amount must be positive, '5000' gives Balance 1000 is less than 5000, and '300' succeeds with new balance 700. finally prints after every attempt.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which block always runs, error or not?

Exercise 2 True / False

A bare except: is the best way to handle errors.

Exercise 3 Fill in the Blank

Signal an error yourself with the ___ keyword.

Frequently Asked Questions

else runs only when the try block raised no exception. finally runs every time, whether there was an error or not, so it is used for cleanup like closing connections.