In python programming language, you will see several built-in exceptions but sometimes user needs to create own exception to serve a specific purpose.
Here in this article, we will learn about user defined exceptions or Python custom exception with the help of examples.
Creating custom exception
In python, the users can create there own custom exceptions by creating a new exception class. A new exception class is derived from the in-built exception class directly or indirectly. Similar to standard exceptions in python, mostly all exceptions are named with the ending "Error" but it is not mandatory. Python custom exceptions can perform anything that a normal class can perform but generally the user-defined exception class is made simple and concise.
# A python program to illustrate how to create user-defined exception# Here, class Error is derived from super class Exception
class Error(Exception):
# Constructor or Initializer
def __init__(self, hello):
self.hello = hello
# __str__ is to print() the value
def __str__(self):
return(repr(self.hello))
try:
raise(Error(9*2))
# Value of Exception is stored in error
except Error as error:
print('Opps!! A New Exception occurred: ',error.hello
Output
File "<string>", line 30print('Oops!! A New Exception occurred: ',error.value
^
SyntaxError: unexpected EOF while parsing
Errors Derived From Super Class Exception
When a module needs to handle specific or distinct errors then we creates the superclass exceptions. We can create a superclass exception by make a base class for exception which is defined by that module. And after that, to create specific exception classes for various error conditions, a subclass is defined.
# A Python program where class Error is derived from super class Exceptionclass Error(Exception):
# Error is derived class for Exception, but Base class for exceptions in this module
pass
class TransitionError(Error):
# Raised when an operation attempts a state transition that's not allowed.
def __init__(self, hello, bye, tc):
self.hello = hello
self.bye = bye
# An Error message thrown is saved in msg
self.tc = tc
try:
raise(TransitionError(5,6*2,"Not Allowed!!"))
# The Value of Exception is stored in error
except TransitionError as error:
print('Exception occurred: ',error.tc)
Output
Exception occurred: Not Allowed!!
How to use Standard Exception Class as Base class?
In python, we can derive an exception from standard exception class. Here in the following illustration, you will see how can we use a standard exception i.e., runtime error (when a generated error doesn't fall in any category then it causes the runtime error) as a base class and drive an exception i.e., network error from it.
# A Python program to illustrate Standard Exception Class as Base class# NetworkError has base RuntimeError and not Exception
class NetError(RuntimeError):
def __init__(self, arg):
self.args = arg
try:
raise NetError("Base RuntimeError")
except NetError as e:
print(e.args)
Output
('B', 'a', 's', 'e', ' ', 'R', 'u', 'n', 't', 'i', 'm', 'e', 'E', 'r', 'r', 'o', 'r')
Customising exception classes
In python, the exception class can be further customised to accept parameters according to our requirements. But for this, the user must have the basic knowledge of Object Oriented Programming (OOP).
class NonValidAge(Exception):""" It will Raised when the age of the person is less than 18"""
pass
def driving_license(age):
if age < 18:
raise NonValidAge
driving_license(16)
Output
Traceback (most recent call last):File "<string>", line 7, in <module>
File "<string>", line 6, in driving_license
__main__.NonValidAge
By overriding the __str__() function, we can customise the exception message. Let's see it in the following example;
class NonValidAge(Exception):"""It Raised when the age of the person is less than 18"""
def __str__(self):
return "The Age of the should be greater than 18 years."
def driving_license(age):
if age < 18:
raise NonValidAge
driving_license(16)
Output
Traceback (most recent call last):File "<string>", line 8, in <module>
File "<string>", line 7, in driving_license
__main__.NonValidAge: The Age of the should be greater than 18 years.
Conclusion
Above we have discussed about user defined exceptions or Python custom exception with the help of examples. In python programming language, you will see several built-in exceptions but sometimes user needs to create own exception to serve a specific purpose. The users can create there own custom exceptions by creating a new exception class. A new exception class is derived from the in-built exception class directly or indirectly.