0% found this document useful (0 votes)
7 views15 pages

Python Exception Handling Guide

The document covers exception handling in Python, explaining what exceptions are, their characteristics, and mechanisms for handling them using try, except, and finally blocks. It also introduces basic concepts of Python for data analysis, including the use of Pandas Series and DataFrames, along with examples of creating, manipulating, and handling missing data. Additionally, it provides sample programs demonstrating exception handling and data analysis techniques.

Uploaded by

shivansh jaiswal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views15 pages

Python Exception Handling Guide

The document covers exception handling in Python, explaining what exceptions are, their characteristics, and mechanisms for handling them using try, except, and finally blocks. It also introduces basic concepts of Python for data analysis, including the use of Pandas Series and DataFrames, along with examples of creating, manipulating, and handling missing data. Additionally, it provides sample programs demonstrating exception handling and data analysis techniques.

Uploaded by

shivansh jaiswal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Contents

Contents 1

1 Exception Handling in Python 3


1.1 What is an Exception?................................................................................................3
1.2 Exception Handling Mechanisms...............................................................................4
1.3 The Except Clause......................................................................................................4
1.4 Try-Finally Clause.......................................................................................................5
1.5 User-Defined Exceptions............................................................................................6

2 Basics of Python for Data Analysis 9


2.1 Introduction to Python for Data Analysis.....................................................................9
2.2 Introduction to Series...................................................................................................9
2.3 Introduction to DataFrames........................................................................................10
2.4 Conclusion................................................................................................................11
Contents

Contents 1

1 Exception Handling in Python 3


1.1 What is an Exception? ................................................................................................. 3
1.2 Exception Handling Mechanisms ............................................................................... 4
1.3 The Except Clause ...................................................................................................... 4
1.4 Try-Finally Clause....................................................................................................... 5
1.5 User-Defined Exceptions ............................................................................................ 6

2 Basics of Python for Data Analysis 9


2.1 Introduction to Python for Data Analysis..................................................................... 9
2.2 Introduction to Series................................................................................................... 9
2.3 Introduction to DataFrames........................................................................................10
2.4 Conclusion ................................................................................................................11
1 Exception Handling in Python

1.1 What is an Exception?


An exception in Python is an event that disrupts the normal flow of a program’s
execution, typically due to errors like division by zero or accessing non-existent files.
Exceptions al- low programs to handle errors gracefully, preventing crashes, which is
critical in data analysis workflows.

Key Characteristics
• Runtime Errors: Exceptions occur during execution, not compilation.

• Hierarchy: All exceptions inherit from BaseException. Common subclasses in-


clude Exception, ArithmeticError, and LookupError.

• Propagation: Unhandled exceptions propagate up the call stack.

Why Exceptions Matter


In data analysis, unhandled exceptions can halt processing pipelines. For example, a FileNotFoundError
when loading a dataset can be caught to log the issue and continue with alternative data.

Example of an Exception

1 # This raises a ZeroDivisionError


2 result = 10 / 0
3
print(result)
Output: ZeroDivisionError: division by zero

Common Built-in Exceptions


• ValueError: Invalid value (e.g., int(’abc’)).

• TypeError: Incompatible types (e.g., ’a’ + 1).

• IndexError: Out-of-range index.


4 CHAPTER 1. EXCEPTION HANDLING IN PYTHON

• KeyError: Missing dictionary key.

• FileNotFoundError: Non-existent file.

1.2 Exception Handling Mechanisms


Python uses try, except, else, and finally blocks to handle exceptions, ensuring robust
code, especially in data processing.

Basic Structure
The try block contains risky code. If an exception occurs, control jumps to except. The
else block runs if no exception occurs, and finally always executes for cleanup.

Flow of Execution
1. Execute try block.

2. If no exception, run else (optional).

3. If exception, match to except clauses.

4. Run finally regardless.

1.3 The Except Clause


The except clause catches specific or all exceptions raised in try.

Syntax

1 try:
2
3
# Code that might
4
fail except ExceptionType
as e:

Catching Specific Exceptions

1 try:
2
3
num = int(input("Enter a number: "))
4
result = 10 / num
5 except ValueError as ve:
6 print(f"Invalid input: {ve}")
7
except ZeroDivisionError as zde:
1.4. TRY-FINALLY CLAUSE 5

Catching Multiple Exceptions


1 try:
2
3
# Risky code
4 except (ValueError, TypeError) as e:
print(f"Error: {e}")

Catching All Exceptions


1 try:
2
3
# Code
4 except Exception as e:

Best Practices
• Catch specific exceptions first.

• Use as e for error details.

• Log exceptions in production code using logging.

1.4 Try-Finally Clause


The finally block ensures cleanup actions, like closing files, execute regardless of excep-
tions.

Syntax

1 try:
2
3
# Code that might raise exception
4
finally:

# Cleanup code

Example

1 file = None
2 try:
3
file = open(’[Link]’, ’r’)
4
content = [Link]()
5
print(content)
6
7 finally:
8
9
if file:
6 CHAPTER 1. EXCEPTION HANDLING IN PYTHON

Combining with Except


1 try:
2
3
# Code
4 except Exception as e:
5 print(e)
6
finally:

Use in Data Analysis


Use finally to close database connections or free memory in long-running scripts.

The Else Clause


The else block runs only if no exception occurs.
1 try:
2
3
result = 10 / 2
4
except ZeroDivisionError:
5 print("Error")
6 else:
7
8 print("Success:",
result) finally:

1.5 User-Defined Exceptions


Custom exceptions are created by subclassing Exception, useful for domain-specific errors.

Creating a Custom Exception


1 class InvalidDataError(Exception):
2
3
def init (self, message="Invalid data
4
provided"): [Link] = message

super(). init ([Link])

Raising Custom Exceptions


1 def validate_data(data):
2
3
if not isinstance(data, int):
4 raise InvalidDataError("Data must be an integer")
5 return data
6
7
8
try:
9
validate_data("abc")
1.5. USER-DEFINED EXCEPTIONS 7

Chaining Exceptions
1 try:
2
3
1 / 0
4 except ZeroDivisionError as zde:
2 Basics of Python for Data Analysis

2.1 Introduction to Python for Data Analysis


Python’s simplicity and libraries like Pandas, NumPy, and Matplotlib make it ideal for data
analysis. This section focuses on Pandas’ Series and DataFrames.

2.2 Introduction to Series


A Pandas Series is a one-dimensional labeled array, like a spreadsheet column.

Creating a Series
1 import pandas as pd
2 import numpy as np
3
4 s = [Link]([1, 3, 5, [Link], 6, 8])
5 print(s)

From Dictionaries
1 s = [Link]({’a’: 1, ’b’: 2, ’c’: 3})

Custom Index
1 s = [Link]([10, 20, 30], index=[’Jan’, ’Feb’, ’Mar’])

Accessing and Operations


• Index: s[0] or s[’Jan’].
• Slicing: s[1:3].
• Arithmetic: s * 2.
• Statistics: [Link](), [Link]().
10 CHAPTER 2. BASICS OF PYTHON FOR DATA ANALYSIS

Missing Data

1 [Link]()
2 [Link](0)

2.3 Introduction to DataFrames


A DataFrame is a two-dimensional labeled structure, like a table.

Creating DataFrames

1 data = {
2
3
’Name’: [’Alice’, ’Bob’, ’Charlie’],
4
’Age’: [25, 30, 35],
5 ’City’: [’NY’, ’LA’, ’Chicago’]
6
7
}

Accessing Data
• Columns: df[’Age’].

• Rows: [Link][0], [Link][0].

• Subsets: [Link][:, ’Name’:’Age’].

Manipulating Data

1 df[’Salary’] = [50000, 60000, 70000]


2
3
[Link](’City’, axis=1)
[Link](columns={’Age’: ’Years’})

Grouping and Merging

1 [Link](’City’)[’Age’].mean()
2 [Link](df1, df2, on=’key’)

Handling Missing Data

1 [Link]()
2 [Link](0)
1 Exception Handling Programs
Program 1: Handle Division by Zero
Problem: Write a Python program to perform division of two user-input numbers and handle
the ZeroDivisionError using try-except.
1 try:
2 a = float(input("Enter numerator: "))
3

4 b = float(input("Enter denominator: ")) result = a / b


5
except ZeroDivisionError as zde:
6

7 print(f"Error: Cannot divide by zero. {zde}") else:


8
print(f"Result: {result}")

Explanation: The program prompts for two numbers and attempts division. The try block
contains the risky operation. If the denominator is zero, ZeroDivisionError is caught,
and an error message is printed. The else block runs if no exception occurs.
Output: Enter numerator: 10 Enter denominator: 0 Error: Cannot
divide by zero. division by zero

Program 2: Handle Multiple Exceptions


Problem: Write a program to convert user input to an integer and divide 100 by it, handling
both ValueError and ZeroDivisionError.
1 try:
2

3 num = int(input("Enter a number: ")) result = 100 / num


4
except ValueError as ve: print(f"Invalid input: {ve}")
5

6 except ZeroDivisionError as zde: print(f"Cannot divide by zero:


7 {zde}")
8

9 else:

Explanation: The try block attempts to convert input to an integer and perform division.
ValueError handles non-integer inputs, and ZeroDivisionError catches division
by zero. Specific exceptions ensure precise error handling.
Output: Enter a number: abc Invalid input: invalid literal for int()
with base 10: ’abc’

Program 3: Try-Finally for File Handling


Problem: Write a program to read a file and ensure it is closed using try-finally, handling
FileNotFoundError.
1 file = None try:
2

3
file = open("[Link]", "r") content = [Link]()
4 print(content)
5
except FileNotFoundError as fnf: print(f"Error: File not found. {fnf}")
6

7 finally:
8

9
if file:
10
[Link]()
11 print("File closed.")

Explanation: The try block attempts to open and read a file. FileNotFoundError is
caught if the file doesn’t exist. The finally block ensures the file is closed, preventing
resource leaks.
Output: Error: File not found. [Errno 2] No such file or directory:
’[Link]’ File closed.

Program 4: User-Defined Exception


Problem: Create a custom exception NegativeNumberError to validate that a user-input
number is positive.
1 class NegativeNumberError(Exception):
2

3 def init (self, message="Number must be positive"): [Link] =


4 message
5
super(). init ([Link])
6

9
def check_positive(num): if num < :
10
raise NegativeNumberError() return num
11

12

13
try:
14

15
num = int(input("Enter a positive number: ")) result =
16
check_positive(num)
17

18 print(f"Valid number: {result}") except


NegativeNumberError as nne:
Explanation: A custom exception NegativeNumberError is defined. The checkpositivefunctionraise
Output: Enter a positive number: -5 Error: Number must be positive

Program 5: Exception Chaining


Problem: Write a program to handle a ZeroDivisionError and raise
a custom MathError with chaining.
1 class MathError(Exception): pass
2

4
try:
5

6 result = 1 / 0
7
except ZeroDivisionError as zde:
Explanation: The program attempts division by zero, catches ZeroDivision
and raises a custom MathError with the original exception chained
using from. This preserves the traceback for debugging.
Output: Traceback (most recent call last): File "<stdin>", line
2, in <module> ZeroDivisionError: division by zero ...
MathError: A mathematical error occurred

2 Python for Data Analysis Programs


Program 6: Create and Manipulate a Series
Problem: Write a program to create a Pandas Series from a list,
calculate its mean, and handle missing values.
1 import pandas as pd import numpy
2 as np
3

5
try:
6

7 s = [Link]([10, 20, [Link], 30, 40]) print("Original Series:\


8 n", s) print("Mean:", [Link]())
9

10 s_filled = [Link]([Link]())
11
print("Series after filling NaN:\n", s_filled) except Exception as e:

Explanation: A Series is created with a missing value ([Link]).


The mean is computed, and fillna replaces NaN with the mean. Exception
handling ensures robustness.
Output: Original Series: 0 10.0 1 20.0 2 NaN 3 30.0 4 40.0 dtype:
float64 Mean: 25.0 Series after filling NaN: 0 10.0 1 20.0 2 25.0
30.0 4 40.0 dtype: float64

Program 7: DataFrame Creation and Filtering


Problem: Create a DataFrame from a dictionary and filter rows where
age is greater than 25.
1 import pandas as pd
2

5
try:
6
data = {
7

8 ’Name’: [’Alice’, ’Bob’, ’Charlie’, ’David’], ’Age’: [22, 30, 27, 24],
9

10
’City’: [’NY’, ’LA’, ’Chicago’, ’Boston’]
11
}
12 print("Filtered DataFrame (Age > 25):\n", filtered_df) except Exception as e:
13

14
print(f"Error: {e}")

Explanation: A DataFrame is created from a dictionary. Boolean


indexing filters rows where Age > 25. Exception handling catches
potential errors.
Output: Original DataFrame: Name Age City 0 Alice 22 NY 1 Bob
30 LA 2 Charlie 27 Chicago 3 David 24 Boston Filtered DataFrame
(Age > 25): Name Age City 1 Bob 30 LA 2 Charlie 27 Chicago

Program 8: Grouping in DataFrame


Problem: Create a DataFrame and compute the average age per city
using groupby.
1 import pandas as pd
2

4
try:
5

6 data = {
7

8 ’Name’: [’Alice’, ’Bob’, ’Charlie’, ’David’], ’Age’: [22, 30, 27, 24],
9
’City’: [’NY’, ’LA’, ’NY’, ’LA’]
10

11 }
12

13 df = [Link](data)

Explanation: The DataFrame is grouped by City, and the mean Age


is calculated. Exception handling ensures robustness.
Output: Average Age per City: City LA 27.0 NY 24.5 Name: Age,
dtype: float64

Program 9: Merging DataFrames


Problem: Merge two DataFrames on a common column and handle missing
keys.
1 import pandas as pd
2

5
try:
6
df1 = [Link]({ ’ID’: [1,
7
2, 3],
8

9 ’Name’: [’Alice’, ’Bob’, ’Charlie’]


10
})
11 })
12

13 merged_df = [Link](df1, df2, on=’ID’, how=’inner’) print("Merged


14 DataFrame:\n", merged_df)
15
except Exception as e:

Explanation: Two DataFrames are merged on the ID column using


an
inner join. Exception handling catches potential issues, like
mismatched keys.
Output: Merged DataFrame: ID Name Salary 0 1 Alice 50000 1
2
Bob 60000
Program 10: Series with Custom Index
Problem: Create a Pandas Series with a custom index and
sort by values.
import
1 pandas as pd
2

4
try:
5 s = [Link]([100, 50, 200, 75], index=[’Jan’, ’Feb’, ’Mar’, ’ Apr’])
6

7 print("Original Series:\n", s) sorted_s =


8 s.sort_values() print("Sorted Series:\n", sorted_s)
9
except Exception as e:

Explanation: A Series is created with month names as


indices. The
[Link].
Output: Original Series: Jan 100 Feb 50 Mar 200 Apr 75
dtype:
int64 Sorted Series: Feb 50 Apr 75 Jan 100 Mar 200 dtype:
int64

You might also like