DEV Community

trishareddy11
trishareddy11

Posted on

2 2

User-defined Exceptions in Python

In Python user-defined exceptions ,users can define custom exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from the built-in Exception class.

CREATING A USER-DEFINED EXCEPTION CLASS

Here we created a new exception class i.e. User_Error. Exceptions need to be derived from the built-in Exception class, either directly or indirectly. Let’s look at the given example which contains a constructor and display method within the given class.

#class MyError is extented from super class Exception
class User_Error(Exception):
# constructor method
def __init__(self,value):
self.value = value
# __str__display function
def __str__(self):
return(repr(self.value))
try:
raise(User_Error("User defined error"))
# Value of Exception is stored in error
except User_Error as error:
print('A New Exception occured:',error.value)

CREATING A USER-DEFINED EXCEPTION CLASS (USING MULTIPLE INHERITENCE)

Derived class Exceptions are created when a single module handles multiple several distinct errors. Here we created a base class for exceptions defined by that module. This base class is inherited by various user-defined class to handle different types of errors.

# define python user-defined exceptions
class Error(Exception):
"""Base clase for other exceptions"""
pass
class Dividebyzero(Error):
"""Raised when the input value is zero"""
pass
try:
i_num = int(input("Enter a number: "))
if i_num ==0:
raise Dividebyzero
except Dividebyzero:
print("Input value is zero, try again!")
print()

Creating a User-defined Exception class (standard Exceptions)

Runtime error is a built-in class which is raised whenever a generated error does not fall into mentioned categories. The program below explains how to use runtime error as base class and user-defined error as derived class.

# User defined error
class Usererror(RuntimeError):
def __init__(self,arg):
self.args = arg
try:
raise Usererror("usererror")
except Usererror as e:
print (e.args)

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

Image of PulumiUP 2025

Let's talk about the current state of cloud and IaC, platform engineering, and security.

Dive into the stories and experiences of innovators and experts, from Startup Founders to Industry Leaders at PulumiUP 2025.

Register Now

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay