Unit 5: Exception Handling



Exception Handling in Python

An exception is a runtime error that occurs during program execution and stops the normal flow of the program.

Common Examples

  • Division by zero
  • File not found
  • Invalid input

print(10 / 0) # ZeroDivisionError

What is Exception Handling?

Exception handling is a mechanism to handle runtime errors gracefully so that the program does not crash suddenly.

Python uses:

  • try
  • except
  • finally

try and except Clause

Syntax

try: statement except: statement

Example

try: x = int(input("Enter number: ")) print(10 / x) except: print("Error occurred")

Handling Specific Exceptions

try: a = int(input()) print(10 / a) except ZeroDivisionError: print("Cannot divide by zero") except ValueError: print("Invalid input")

try – finally Clause

The finally block always executes, whether an exception occurs or not.

Syntax

try: statement finally: statement

Example

try: file = open("data.txt", "r") print(file.read()) finally: file.close()

try – except – finally (Complete Form)

try: print(10 / 0) except: print("Error handled") finally: print("Program ended")

User-Defined Exceptions

User can create custom exceptions using Exception class.

Syntax

class MyError(Exception): pass

Example

class AgeError(Exception): pass age = int(input("Enter age: ")) if age < 18: raise AgeError("Age must be 18 or above") else: print("Valid age")

Important Exception Keywords 

KeywordUse
tryTest risky code
exceptHandle error
finallyAlways execute
raiseThrow exception

Important Exam Points (Exception Handling)

  • Exceptions occur at runtime
  • except prevents program crash
  • finally always executes
  • User-defined exceptions improve control
  • Multiple except blocks allowed

Basics of Python for Data Analysis

Python is widely used in Data Analysis due to libraries like NumPy, Pandas, Matplotlib.

Why Python for Data Analysis?

  • Easy syntax
  • Powerful libraries
  • Handles large datasets
  • Strong community support

Introduction to Pandas Library

Pandas is a Python library used for data manipulation and analysis.

Main Data Structures

  • Series
  • DataFrame

import pandas as pd

Introduction to Series

A Series is a one-dimensional labeled array.

Example

import pandas as pd s = pd.Series([10, 20, 30, 40]) print(s)

Series with Custom Index

s = pd.Series([85, 90, 78], index=["Math", "Sci", "Eng"]) print(s)

Series Properties

PropertyMeaning
valuesData
indexLabels
dtypeData type

Introduction to DataFrame

A DataFrame is a two-dimensional table-like structure (rows & columns).

Diagram (Conceptual)

Name Age Marks 0 Amit 20 85 1 Jay 22 90 2 Ravi 21 88

Creating DataFrame

data = { "Name": ["Amit", "Jay", "Ravi"], "Age": [20, 22, 21], "Marks": [85, 90, 88] } df = pd.DataFrame(data) print(df)

Accessing DataFrame Data

print(df["Name"]) # Column print(df.loc[0]) # Row

Series vs DataFrame

FeatureSeriesDataFrame
Dimension1D2D
StructureSingle columnRows & columns
UseSingle dataTabular data

Important Exam Points (Data Analysis)

  • Pandas is core library for data analysis
  • Series is 1D, DataFrame is 2D
  • DataFrame works like Excel sheet
  • Labels make data easy to handle

Frequently Asked Exam Questions

  • What is exception handling?
  • Explain try-except-finally
  • What is user-defined exception?
  • Define Series and DataFrame
  • Difference between Series and DataFrame