If you are working with Python and dealing with exceptions, you are likely using the built-in exception classes. However, there are times when you might want to create your exception class. An exception is a programming construct that permits code to terminate abnormally, typically with an error message. In most cases, exceptions are used to prevent the execution of unintended or harmful programs.
Python is a universal language that can be used for various purposes. By using user-defined exceptions in Python, you can customize the behaviour of specific exceptions. This can be especially useful when developing code that needs to handle specific situations. So if you want to add more flexibility and realism to your Python programs, look no further than the user-defined exception class.
Table of Contents
What is User-defined Exception?
The user-defined exception is a built-in exception class in the Python programming language that allows you to create your exceptions. This can be extremely useful for situations where an error occurs, but you do not know precisely what it is or how to fix it. By defining your exception, you can handle the situation differently from one instance to the next, making recovering from errors much easier. In addition, several subclasses are established to generate different exception classes depending on the error conditions.
Creating Custom Exception
Custom exception class are special classes that can be used to handle unexpected situations while programming. When an exception occurs, Python automatically uses a Custom Exceptions class, allowing you to inspect the program’s state and take appropriate action. Although the custom class must not be empty, this is considered an error in exception handling.
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return(repr(self.value))
try:
raise(MyError(30/10))
except MyError as error:
print('A New Exception occurred: ', error.value)
Output

User-defined with Multiple Inheritance
User-defined classes with multiple inheritances allow you to create custom objects that can be extended and inherited. This enables you to define your properties, methods, and events on these custom objects without creating a separate class for each.
class Error(Exception):
pass
class multiplybyzero(Error):
pass
try:
i_num = int(input("Enter a number: "))
if i_num == 0:
raise multiplybyzero
except multiplybyzero:
print("Input value is zero, enter another value")
print()
Output

User-defined Standard Exception
The user-defined standard exception is a feature in the Python programming language that gives you more control over how exceptions are handled. Using this feature, you can create your own exceptions that can be treated differently from others. For example, you might want to handle user-defined exceptions, mainly, so they do not cause crashes or stop program execution altogether.
help(Exception)
Output


User-define Standard Exception as a Base Class
A user-defined standard exception is a base class that can be used to create custom exceptions in Python. This is helpful if you need to handle specific situations that do not fit into the built-in exceptions. Using a user-defined standard exception can keep your code concise and organized without resorting to duplicate logic or clunky Using try/except blocks.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
try:
raise Networkerror("Network error")
except Networkerror as e:
print(e.args)
Output

Deriving Error from Super Class Exception
In Python, when you derive a class from another class, the superclass’s methods become available in your own derived class. This is known as deriving error, and it can be not very clear if you are not familiar with how it works. When an exception is raised inside a derived class, the superclass’s methods are automatically called to try and resolve the problem.
class Error(Exception):
pass
class TransitionError(Error):
def __init__(self, prev, nex, msg):
self.prev = prev
self.next = nex
self.msg = msg
try:
raise(TransitionError(20, 20/10, "division Not Allowed"))
except TransitionError as error:
print('Exception occurred: ', error.msg)
Output

Python User-define Exception: Using Assert Statement
Assert is a keyword in Python that allows you to implement user-defined exceptions. Assertions are blocks of code that you can insert into your program to check conditions and throw an error message or execute specific actions if they are not met. This helps to prevent these types of errors from happening in your application and keeps everything running smoothly.
try:
time= 13
print("time is:")
print(time)
assert age>=12
except AssertionError:
print("Input 12 hrs time format")
Output

Also learn in detail, python exception handling
FAQs
Are user-defined exceptions checked or unchecked?
Since they are extended with the Exception class, a superclass for all exceptions, user-defined exceptions is known as checked exceptions.
What type of exceptions can be ignored at compile time?
Runtime Exceptions are those that occur during execution. These exceptions are detected during compilation but not during runtime. Therefore, no compile error occurs when a program throws an unchecked exception that is not declared.
Can user-defined exception extends Runtime Exception?
If you want to make it unchecked, extend the custom exception with Exception; otherwise, extend it with RuntimeException. The throws clause of the code method does not need to mention any RuntimeException subclasses that may be thrown but not caught during the execution of the method.
Conclusion
In this blog, we walked you through how to create a user-defined exceptions in Python. You must have realized the power of an exception in handling errors. However, it can also be used to your advantage if you create a robust set of rules that match the error and handle them accordingly.The best way to do this is by creating your own exceptions library (or modules) in Python that only contain classes with well-defined behaviour. Thanks to the newly added user-defined exceptions feature, it will be more accessible than ever to deal with confusing errors.