Python Exceptions

Introduction Reading Time: 10 min

Table of Contents

Description

An exception is an error that occurs during the execution of a program, disrupting the normal flow of the program. Python provides a mechanism to catch and handle these exceptions using try, except, else, and finally blocks. Without handling, exceptions cause the program to crash. With proper handling, you can gracefully recover or inform the user.

Prerequisites

  • Basic understanding of control flow
  • Familiarity with functions
  • Understanding syntax and runtime errors

Examples

Here's a simple program in Python:

✅ Basic Try-Except Block
try:
    # Code that might cause an error
    x = 10 / 0
except ZeroDivisionError:
    # Code that runs if exception occurs
    print("Cannot divide by zero.")
✅ Catching Multiple Exceptions
try:
    a = int(input("Enter a number: "))
    b = 10 / a
except ValueError:
    print("You must enter a number.")
except ZeroDivisionError:
    print("Cannot divide by zero.")
✅ Using else and finally
try:
    num = int(input("Enter a number: "))
except ValueError:
    print("Invalid input.")
else:
    # Runs if no exception occurs
    print("You entered:", num)
finally:
    # Always runs, whether or not exception occurred
    print("Execution finished.")
✅ Raising Custom Exceptions
def withdraw(amount):
    if amount < 0:
        # Raise your own exception
        raise ValueError("Negative amount not allowed.")
    print("Withdrawn:", amount)

# Example call
withdraw(100)

      

Real-World Applications

Handling file not found errors

Managing user input validation

Catching network or API call failures

Logging and retrying database operations

Ensuring programs don’t crash unexpectedly

Where topic Can Be Applied

Web Development: Handling form errors and HTTP exceptions

Data Science: Handling file loading and parsing exceptions

APIs: Gracefully handling request timeouts, 404s, etc.

Finance Applications: Input validation and business rule exceptions

System Utilities: Managing hardware or OS-related errors

Resources

Topic video source

A comprehensive video

Watch

Python pdf

pdf on topic

Visit

Interview Questions

What is an exception in Python?

What is the difference between syntax errors and exceptions?

What is the purpose of finally?

Can we catch multiple exceptions in one block?

How do you raise a custom exception?

What happens if you don’t handle an exception?