Exception Handling and Modules in Python.pptx

shilpamathur13 2 views 30 slides Oct 30, 2025
Slide 1
Slide 1 of 30
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30

About This Presentation

Exception handling in Python manages runtime errors using try, except, and assert statements to ensure smooth program execution. Modules and packages help organize code into reusable components, which can be created, documented, tested, imported, and exported for better modular programming.


Slide Content

Module 4 Exception Handling and Packages

Errors in the program 1. Syntax Errors: Definition: These are mistakes in the structure or format of the code that prevent the program from being interpreted correctly by the Python interpreter. Cause: Syntax errors occur when the code violates the rules of Python's language. Examples: 1. Colon: Forgetting a colon (:) after a control statement like if, for, while. if x == 5 # Missing colon print("x is 5") 2. Unclosed Parentheses: F orgetting to close parentheses or brackets. print("Hello" # Missing closing parenthesis) 3. Incorrect Indentation: Python requires consistent indentation to define code blocks. def my_function(): print("Hello") # Incorrect indentation. Impact: Syntax errors prevent the program from running entirely. Python will immediately stop execution and display a syntax error message with details of where the error occurred.

2. Runtime Errors (Exceptions): Definition: These errors occur after the program starts running and are typically caused by invalid operations. Unlike syntax errors, runtime errors occur during execution when Python encounters an operation that it cannot handle. Cause: Runtime errors can be caused by issues such as dividing by zero, accessing a variable that hasn’t been defined, or trying to open a file that doesn’t exist. Types of Exceptions: ZeroDivisionError: Occurs when attempting to divide by zero. x = 10 / 0 # Raises ZeroDivisionError NameError: Occurs when trying to access a variable that hasn’t been defined. print(my_var) # Raises NameError because 'my_var' is not defined

IndexError: Occurs when accessing an index that is out of the bounds of a list or tuple. my_list = [1, 2, 3] print(my_list[5]) # Raises IndexError as index 5 is out of range TypeError: Occurs when an operation or function is applied to an object of an inappropriate type. print("Age: " + 30) # Raises TypeError because a string and integer are being concatenated FileNotFoundError: Occurs when trying to open a file that doesn’t exist. open("nonexistent_file.txt") # Raises FileNotFoundError

Handling Exceptions: Runtime errors can be anticipated and managed using try-except blocks. This allows the program to handle exceptions gracefully, without crashing. Impact: While syntax errors prevent the program from running, runtime errors occur during execution and can stop the program unless handled using proper exception handling techniques.

1. Which of the following is a Syntax Error in Python? A) Dividing a number by zero B) Forgetting to close a parenthesis in a function C) Accessing a list element out of range D) Trying to open a file that doesn’t exist 2. What type of error occurs when you try to access a variable that hasn’t been defined? A) IndexError B) ZeroDivisionError C) NameError D) TypeError 3. Which of the following errors can be handled using a try-except block in Python? A) SyntaxError B) NameError C) ZeroDivisionError D) Both B and C

Exceptions, Exception Handling Exception Handling: This refers to the process of detecting, capturing, and managing runtime errors (exceptions) in a controlled manner using constructs like try, except, finally, and raise. The main goal is to allow the program to continue running or terminate gracefully when an error occurs. Error Handling Constructs: try Block: Contains code that may potentially raise an exception. except Block: Defines how to handle specific exceptions if they occur. finally Block: Executes code that must run regardless of whether an exception was raised or not, often used for cleanup tasks like closing files.

Exception handling in Python is essential for making programs more robust, preventing crashes, and managing unexpected errors gracefully. Here’s why it’s important: 1. Avoiding Program Crashes ● Without exception handling, an unexpected error (like dividing by zero or accessing an undefined variable) will terminate the program, causing a crash. ● Exception handling allows the program to handle these situations without stopping execution.

2. Graceful Error Handling ● It allows the program to respond to errors in a controlled way, such as logging the error, notifying the user, or providing an alternative flow. ● The user can be informed of what went wrong without seeing a confusing error message

3. Handling Multiple Types of Errors ● Different parts of your code may throw different types of errors. Exception handling allows you to catch and handle specific errors separately.

4. Maintaining Program Flow ● If an error occurs during a specific operation, you may want to skip that operation and continue with the rest of the program. Exception handling enables this behavior, allowing the program to maintain its flow.

5. Cleaning Up Resources ● Some operations, like file handling or network connections, require proper cleanup. Using exception handling ensures that resources like open files or database connections are properly closed even if an error occurs.

Write a Python function that divides two numbers and uses exception handling to manage potential ZeroDivisionError. Include code to ensure the program continues to run even if an error occurs during division.

Raise Error In Python, the raise statement is used to manually trigger an exception . age = -5 if age < 0: raise ValueError("Age cannot be negative!") Output: ValueError: Age cannot be negative!

The Assert Statement assert is mainly for development and debugging, not for handling runtime errors in production. The assert statement is useful to ensure that a given condition is True. If it is not true, it raises AssertionError. The syntax is as follows: assert condition, message If the condition is False, then the exception by the name AssertionError is raised along with the ‘message’ written in the assert statement. If ‘message’ is not given in the assert statement, and the condition is False, then also AssertionError is raised without message.

Creating Modules and Packages In Python, modules are single files that contain Python code. They can include variables, functions, and classes, and are used to group related code into a reusable format. Modules help in organizing code logically, making it easier to maintain and understand. Import Statement: A statement used to include the definitions and statements from a module or package into the current namespace. Example: import math, from mypackage import module1. Built-in Module: Modules that are included with Python and provide standard functionality. Examples include math for mathematical operations, random for generating random numbers, and datetime for handling dates and times. import math print(math.sqrt(16)) print(math.pi)

A package is a way of organizing related modules into a single directory (folder). This makes large projects more structured and reusable . Built-in Packages (from Python Standard Library) Some standard packages include: os → file & directory operations sys → system-specific functions json → JSON handling http → HTTP handling collections → specialized data structures

Documenting & Viewing Module 1. Documenting Python Modules Docstrings Definition: Docstrings are string literals that appear right after the definition of a function, method, class, or module. They are used to document what the code does, its parameters, return values, and other relevant information. Format: A docstring is written inside triple quotes (""" or '''). For modules, the docstring should describe the module's purpose and its contents. For functions and methods, it should describe the functionality, parameters, and return values.

Viewing Module Documentation Using Help Function ● Definition: The help() function in Python can be used to view documentation for modules, functions, classes, and methods.