Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Exception Handling in Python

Lesson 23 of 37 in the free Data Science notes on Siksha Sarovar, written by Rohit Jangra.

Exception Handling in Python

Definition: Exception Handling is a mechanism in Python that allows you to gracefully handle runtime errors instead of letting the program crash.Errors are inevitable in programming — a file might not exist, a user might enter invalid input, or a network request might fail.Exception handling ensures your program can respond to these situations intelligently.

---

Errors vs Exceptions

TypeWhen It OccursExampleCan Be Caught ?
Syntax Error Before execution(parsing)print("Hello (missing quote)❌ No (fix the code)
ExceptionDuring execution (runtime)10 / 0 (ZeroDivisionError)✅ Yes (try/except)

---

Common Python Exceptions

ExceptionCauseExample
ZeroDivisionErrorDivision by zero10 / 0
TypeErrorWrong type operation"hello" + 5
ValueErrorCorrect type, wrong valueint("abc")
IndexErrorIndex out of rangelst[100] on a small list
KeyErrorKey not found in dictionaryd["nonexistent_key"]
FileNotFoundErrorFile doesn't existopen("missing.txt")
ImportErrorModule not foundimport nonexistent_module
AttributeErrorObject has no attribute"hello".push("x")
NameErrorVariable not definedprint(undefined_var)
StopIterationIterator exhaustednext() on empty iterator

---

The try-except Block

Syntax:

try:
    # Code that might cause an error
except ExceptionType:
    # Code to handle the error

Example:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
# Output: Cannot divide by zero!

---

Handling Multiple Exceptions

try:
    x = int(input("Enter a number: "))
    result = 10 / x
except ValueError:
    print("Invalid input! Please enter a number.")
except ZeroDivisionError:
    print("Cannot divide by zero!")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

---

The else and finally Clauses

try:
    file = open("data.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found!")
else:
    print("File read successfully!")  # Runs only if NO exception
    print(content)
finally:
    print("Cleanup complete.")       # ALWAYS runs

Purpose of Each Block:

BlockWhen It RunsUse Case
tryAlways (first attempt)Code that might fail
exceptOnly if an exception occursHandle the specific error
elseOnly if NO exception occursSuccess logic
finallyALWAYS (even if exception occurs)Cleanup (close files, connections)

---

Raising Exceptions

You can deliberately raise exceptions using the raise keyword.

def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative!")
    if age > 150:
        raise ValueError("Age seems unrealistic!")
    return age

try:
    set_age(-5)
except ValueError as e:
    print(e)  # Age cannot be negative!

---

Custom Exceptions

You can create your own exception classes by inheriting from the Exception class.

class InsufficientFundsError(Exception):
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        super().__init__(f"Cannot withdraw {amount}. Balance: {balance}")

class BankAccount:
    def __init__(self, balance):
        self.balance = balance

    def withdraw(self, amount):
        if amount > self.balance:
            raise InsufficientFundsError(self.balance, amount)
        self.balance -= amount
        return self.balance

# Usage
try:
    account = BankAccount(1000)
    account.withdraw(1500)
except InsufficientFundsError as e:
    print(e)  # Cannot withdraw 1500. Balance: 1000

---

Exception Handling in Data Science

ScenarioExceptionHow to Handle
Missing CSV fileFileNotFoundErrorPrompt user for correct path
Invalid user input for modelValueErrorValidate input before processing
API request failureConnectionErrorRetry with backoff
Division by zero in calculationsZeroDivisionErrorAdd a check or use try/except
Missing dictionary keyKeyErrorUse .get(key, default) instead
Out-of-memory with large dataMemoryErrorUse chunked processing (chunksize in Pandas)

---

Best Practices

PracticeDescription
Be SpecificCatch specific exceptions, not bare except:
Don't SuppressDon't use empty except: pass — at least log the error
Use finallyFor cleanup operations (closing files, connections)
Validate FirstPrefer validation over exception handling when possible
Custom ExceptionsCreate meaningful exception classes for domain-specific errors
Log ErrorsUse the logging module to record errors for debugging

Summary

  • Exceptions are runtime errors that can be caught and handled gracefully.
  • try/except/else/finally provides a structured way to handle errors.
  • Common exceptions include ValueError, TypeError, KeyError, and FileNotFoundError.
  • raise is used to deliberately trigger exceptions.
  • Custom exceptions make error handling more meaningful and domain-specific.
  • In data science, exception handling is crucial for robust data pipelines and model training.