Sitemap

Python Exception Handling

4 min readJun 28, 2025

--

Table of Contents:

  • Python Exception Handling — Definition and Example
  • Why We Need to Use Exception Handling
  • Advantages of Exception Handling
  • What is Error Handling and Example
  • Difference Between Exception and Error
  • try, except, else, and finally Blocks
  • Common Exceptions in Python with Example and Use Case
  • Python Catching Exceptions
  • Catching Specific Exceptions
  • Catching Multiple Exceptions
  • Raise an Exception

1. Python Exception Handling — Definition and Example

Exception handling in Python is a mechanism to handle runtime errors, allowing the program to continue running instead of crashing.

Example:
try:
result = 10 / 0
except ZeroDivisionError:
print(“You can’t divide by zero!”)

2. Why We Need to Use Exception Handling

— To avoid program crashes.
— To handle unexpected situations gracefully.
— To log and debug errors.
— To provide user-friendly error messages.

Without exception handling:
a = 10 / 0 # Program crashes

With exception handling:
try:
a = 10 / 0
except ZeroDivisionError:
print(“Handled the error, so program won’t crash.”)

3. Advantages of Exception Handling

  • Prevents program crashes.
  • Organizes error-handling logic.
  • Ensures resource cleanup.
  • Provides meaningful messages to users.
  • Code clarity
  • Debugging support
  • Resource cleanup (using finally block)

4. What is Error Handling and Example

Error handling is the process of anticipating, detecting, and resolving programming errors.

Example:
try:
f = open(“file.txt”, “r”)
except FileNotFoundError:
print(“File not found!”)

5. Difference Between Exception and Error

Exception:
— Events that occur during execution
— Can be handled using try-except
— Example: ZeroDivisionError, ValueError

Error:
— Serious problems outside control
— Rarely handled in code
— Example: MemoryError, RecursionError

6. try, except, else, finally Blocks

Press enter or click to view image in full size

try:
num = int(input(“Enter a number: “))
except ValueError:
print(“That’s not a valid number!”)
else:
print(“Success! You entered:”, num)
finally:
print(“Execution finished.”)

7. Common Exceptions in Python with Example & Use Case

Press enter or click to view image in full size

8. Python Catching Exceptions

try:
x = int(“abc”)
except Exception as e:
print(“Exception caught:”, e)

9. Catching Specific Exceptions

try:
result = 10 / int(input(“Enter a number: “))
except ValueError:
print(“Input must be a number.”)
except ZeroDivisionError:
print(“You can’t divide by zero.”)

10. Catching Multiple Exceptions

try:
a = int(“abc”)
b = 10 / 0
except (ValueError, ZeroDivisionError) as e:
print(“Caught error:”, e)

11. Raise an Exception

age = -1
if age < 0:
raise ValueError(“Age can’t be negative”)

Interview Questions on Exception Handling:

  1. What is exception handling in Python?
  2. Why is exception handling important in Python programs?
  3. What is the difference between an error and an exception?
  4. What are the key blocks used in exception handling in Python?
  5. What is the use of the else block in a try-except-else-finally structure?
  6. What is the role of the finally block? Will it execute even if there's an exception?
  7. Can we have multiple except blocks? Give an example.
  8. Can you catch multiple exceptions in a single except block? How?
  9. How do you raise a custom exception in Python?
  10. What is the base class for all exceptions in Python?

Tasks for Practice:

1. User Input Validation System

Get Krishna Chaitanya’s stories in your inbox

Join Medium for free to get updates from this writer.

Build a script that takes user inputs (name, age, email).
— Handle empty input
— Raise ValueError for invalid age (<0)
— Raise custom exception for invalid email (no ‘@’)

2. File Reader Tool

Build a function that opens a file and reads its content.
— Handle FileNotFoundError if the file doesn’t exist
— Handle PermissionError for restricted files
— Use finally to always close the file

3. Safe Division Function

Write a safe_divide(a, b) function that:
— Catches ZeroDivisionError
— Catches TypeError if a or b are not numbers
— Logs errors and returns meaningful messages

4. API Request Handler (Mock Project)

Simulate an API call using a function.
— Raise exception for invalid endpoint
— Handle timeout with a custom TimeoutError
— Use try-except-finally to manage connection lifecycle

5. Dictionary Data Fetcher

Fetch a value from a dictionary by key.
— Handle KeyError and return a default message
— Log access errors for missing keys
— Raise exception if dictionary is empty

6. File Upload Validator

Validate file format and size.
— Raise ValueError for unsupported formats (e.g., .exe)
— Raise custom FileTooLargeException if size > 5MB
— Catch both and return meaningful feedback

7. Student Grade Calculator

Read marks from user, compute grade.
— Handle non-integer input (ValueError)
— Handle marks outside valid range (0–100)
— Raise custom exceptions for invalid scores

8. Database Connection Simulator

Simulate a DB connection (no real DB needed).
— If credentials are wrong, raise PermissionError
— If DB not found, raise ConnectionError
— Use finally block to ‘close’ the connection

9. E-Commerce Cart Price Calculator

Calculate total from cart list (item name, price, quantity).
— Handle missing price or quantity with KeyError
— Handle type errors (e.g., string instead of int)
— Use try-except to process the cart smoothly

10. Exception Logger Utility

Create a utility function log_exception(e) that:
— Accepts an exception object
— Logs error type, message, and timestamp to a file
— Can be reused in any except block

--

--