creating user
defined
exceptions
Custom Error Handling for Better Code
NAME : [Link]
ROLL NO : 24671A7368
SECTION : AIML-B
INTRODUCTION
EXCEPTION BASICS
DEFINITION OF AN EXCEPTION
An exception is an event that occurs during the execution of a
program that disrupts the normal flow of instructions.
•It is a runtime error that can be caused by:
•Invalid input (e.g., dividing by zero)
•Missing files
•Memory issues
•Incorrect data types
Built-in exceptions
overview
These exceptions are automatically raised when a program runs into errors.
EXCEPTION NAME DESCRIPTION
Zero Division Error: Raised when dividing by zero.
Raised when an operation is applied to an
Type Error :
inappropriate type.
Raised when a function receives an
Value Error : argument of correct type but inappropriate
value.
Raised when a sequence subscript is out of
Index Error :
range.
Key Error : Raised when a dictionary key is not found.
FileNotFoundError: Raised when a file or directory is not found.
Import Error : Raised when an import fails
USER-DEFINED
EXCEPTIONS
Creating a user-defined
exception class
To create a user-defined exception in Python, one
must inherit from the base Exception class. A custom
class can include a descriptive name and optional
docstrings to provide clarity about its purpose. By
following this approach, developers can create
meaningful exceptions that serve distinct functions
within their programs.
Raising and handling exceptions
Once a user-defined exception class is created, it can be raised
using the 'raise' keyword. For example, if a certain condition is
met, such as invalid input, the custom exception can be
triggered. To handle exceptions gracefully, Python utilizes the
try and except blocks, which allow developers to manage
unexpected events without crashing the program.
EXAMPLE:
# Step 1: Create a user-defined exception
class AgeTooSmallError(Exception):
pass
# Step 2: Create a function that raises the exception
def check_age(age):
if age < 18:
raise AgeTooSmallError("Age must be at least 18.")
else:
print("Access granted!")
# Step 3: Handle the exception
try:
check_age(15)
except AgeTooSmallError as e:
print("Error:", e)
THANK YOU