0% found this document useful (0 votes)
8 views

Lecture 7-8 Exception Handling-1

Python

Uploaded by

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

Lecture 7-8 Exception Handling-1

Python

Uploaded by

r8889127
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Exception Handling

Exceptions
• Exceptions are unforeseen errors or problems that can occur during
the execution of a Python program.
• These errors can cause the program to terminate abruptly if not
handled properly. Python provides a robust mechanism called
"exception handling" to manage such errors gracefully.
ZeroDivisionError, IndexError,
TypeError, KeyError,
ValueError, NameError
IOError,
ZeroDivisionError,

TypeError,

ValueError,
Types of
IOError,
Exception
IndexError,

KeyError,

NameError
Example of Exception

• 102/0 ZeroDivisionError

• Open(xyz.txt). //xyz.txt not present in the folder IOError

• Int(“Hello”) TypeError

• date_str = "2023-07-32"
ValueError
• date_obj = datetime.strptime(date_str, "%Y-%m-
%d")
Try and Except Statement
• Try and except statements are used to catch and handle exceptions in
Python.
• Statements that can raise exceptions are kept inside the try clause
and the statements that handle the exception are written inside
except clause.
Handling Exception
Find Exception type
ZeroDivisionError: This exception is raised when an attempt is made to
divide a number by zero.
num = int(input("Enter a number: "))
result = 10 / num
TypeError: This exception is raised when an operation or function is
applied to an object of the wrong type.

num = int(input("Enter a number: "))


IOError: This exception is raised when an I/O operation, such as reading
or writing a file, fails due to an input/output error.
with open("non_existent_file.txt", "r") as file:
content = file.read()
IndexError: This exception is raised when an index is out of range for a
list, tuple, or other sequence types.
my_list = [1, 2, 3]
print(my_list[5])
KeyError: This exception is raised when a key is not found in a dictionary.
my_dict = {"name": "John", "age": 30}
print(my_dict["gender"])
NameError: This exception is raised when a variable or function name is
not found in the current scope.

print(x) //x is not defined previously


result = 10 + "5"
result = "Hello" / 2
result = sum(range(1, "5")
num = int("123", base=2)
value = float("12.3.4")
Multiple error possibility
• The finally block, if present, will always be
Finally: Something executed, whether an exception occurs or not.
that must execute • It is used for cleanup operations like closing files
or releasing resources.
• The else clause is executed if no exceptions occur
inside the try block.
Else clause • It is typically used to specify code that should be
executed when the try block runs without any
exceptions.
• Instead of using the built-in exception handling mechanisms, it demonstrates how
Custom to create and use a custom exception.
• Instead of catching a general IOError, which could signify various issues (like
Exception permission errors, file not found, etc.), the custom exception specifies that the error
is related to a missing file.
• Explanation:
• Custom Exception Class:
• Defines a custom exception FileNotFoundError that inherits
from the base Exception class.
• The __init__ method initializes the exception with the file
name.
Custom • The __str__ method provides a custom error message.
Exception: • Function to Read File:
• read_file attempts to open and read a file.
• If successful, it prints the content.
• If an IOError occurs (e.g., the file does not exist), it raises a
FileNotFoundError.
• Main Execution Block:
• The if __name__ == "__main__": block ensures the code
runs only when the script is executed directly.
• It tries to read a file named example.txt.
• If a FileNotFoundError is raised, it prints an error message.
Problem
• You are working on a project to build a custom text processing tool that
reads input from various sources, processes the text data, and stores the
results in an output file. As part of this project, you need to implement a
robust exception handling mechanism to handle potential errors that may
arise during the text processing.
• The tool needs to perform the following steps:
1.Read the input data from a file specified by the user.
2.Process the text data by performing various operations, such as counting
words, calculating character frequencies, and generating word clouds.
3.Store the processed results in an output file.
Task
• Your task is to design a Python program that incorporates appropriate
exception handling to handle the following situations:
1.File Not Found Error: If the user provides an invalid file path or the
input file is not found, your program should raise a custom exception
FileNotFoundError with a suitable error message.
2.Invalid Input Data: During text processing, if any unexpected input
data is encountered (e.g., non-string values or missing data), your
program should raise a custom exception InvalidInputDataError with
relevant details.
3.Disk Space Full: If the output file cannot be written due to insufficient
disk space, your program should raise a custom exception
DiskSpaceFullError
You can use Python's built-in modules, such as os for file
Additionally handling and logging for logging exceptions

• The program should have the following features:


• The custom exception classes should inherit from the base Exception
class and provide meaningful error messages.
• Proper logging should be implemented to capture details about the
exceptions that occur during text processing.
• The program should provide a user-friendly interface, allowing the user to
enter the input file path and choose the desired text processing operations.
• The processed results should be stored in an output file with a suitable
format (e.g., JSON, CSV, or plain text).

You might also like