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

User Defined Exceptions

User-defined exceptions in Python are custom exceptions created by programmers to enforce variable constraints, derived from the built-in Exception class. To create a custom exception, one must define a new class, initialize it with attributes or messages, and optionally override string representation methods. These exceptions can be raised using the 'raise' statement and handled using 'try-except' blocks to manage specific error conditions gracefully.

Uploaded by

pamidi.prameela
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)
18 views

User Defined Exceptions

User-defined exceptions in Python are custom exceptions created by programmers to enforce variable constraints, derived from the built-in Exception class. To create a custom exception, one must define a new class, initialize it with attributes or messages, and optionally override string representation methods. These exceptions can be raised using the 'raise' statement and handled using 'try-except' blocks to manage specific error conditions gracefully.

Uploaded by

pamidi.prameela
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
You are on page 1/ 3

User Defined Exceptions:

User defined exceptions in python are created by programmers to enforce constraints on


the values of the variables in the program can take.
They are derived from the built-in Exception class.
Exceptions need to be derived from the Exception class, either directly or indirectly.
Although not mandatory, most of the exceptions are named as names that end in “Error”
In Python, we can define custom exceptions by creating a new class that is derived from
the built-in Exception class.
 How to Create a User-Defined Exception:
Step 1 − Define the Exception Class
Create a new class that inherits from the built-in "Exception" class This new class will
serve as your custom exception.
Ex:
class MyCustomError(Exception):
pass

Step 2 − Initialize the Exception


Implement the "__init__" method to initialize any attributes or provide custom error
messages. This allows you to pass specific information about the error when raising the
exception.
Ex:
class InvalidAgeError(Exception):
def __init__(self, age, message="Age must be between 18 and 100"):
self.age = age
self.message = message
super().__init__(self.message)

Step 3 − Optionally Override "__str__" or "__repr__"


Override the "__str__" or "__repr__" method to provide a custom string representation of
the exception. This is useful for printing or logging the exception.
Ex:
class InvalidAgeError(Exception):
def __init__(self, age, message="Age must be between 18 and 100"):
self.age = age
self.message = message
super().__init__(self.message)

def __str__(self):
return f"{self.message}. Provided age: {self.age}"
 Raising User-Defined Exceptions:
Once a custom exception is created, we can raise it in code to signify specific error
conditions. Raising user-defined exceptions involves using the raise statement
Syntax:
raise ExceptionType(args)
Ex:
In this example, the "set_age" function raises an "InvalidAgeError" if the age is outside
the valid range .
def set_age(age):
if age < 18 or age > 100:
raise InvalidAgeError(age)
print(f"Age is set to {age}")

 Handling User-Defined Exceptions:


Handling user-defined exceptions in Python refers to using "try-except" blocks to catch
and respond to the specific conditions that custom exceptions represent.
This allows program to handle errors gracefully
Syntax:
try:
# Code that may raise an exception
except ExceptionType as e:
# Code to handle the exception

Ex:
try:
set_age(150)
except InvalidAgeError as e:
print(f"Invalid age: {e.age}. {e.message}")
In the above example, the "try" block calls "set_age" with an invalid age. The "except"
block catches the "InvalidAgeError" and prints the custom error message .
EXAMPLE:
class InvalidAgeError(Exception):
def __init__(self, age, message="Age must be between 18 and 100"):
self.age = age
self.message = message
super().__init__(self.message)
def __str__(self):
return f"{self.message}. Provided age: {self.age}"
def set_age(age):
if age < 18 or age > 100:
raise InvalidAgeError(age)
print(f"Age is set to {age}")
try:
set_age(150)
except InvalidAgeError as e:
print(f"Invalid age: {e.age}. {e.message}")

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy