Set Personalized Exceptions in Python
In this tutorial, you will learn how to set Personalized message for an exception in Python.
Programmers are able to name their own exceptions by creating a new exception class. Python has many built-in exceptions that are present in Exception class.
Exception handling is very important in any programming language. The basic things needed to handle an exception in Python are:
- “try” block: Used to find errors in the code.
- “raise” statement: Used to raise an Exception.
- “except” block: Used to handle Exceptions.
The structure of Exception handling is displayed in the image Exception handling in Python.
Set Personalized message for an exception in Python
Example to set personalized exceptions:
class A(Exception): pass try: raise(A()) except A as e: print("User defined exception")
from the above code, we can get the Output as:
User Defined Exception
Now we see how to raise an exception using a Personalized Message.
try: raise Error('HiThere') except NameError: print('An raise exception !')
As a result of the following code, we get the output as:
An raise exception
- In the above example, try block is used to find errors, raise is used to raise an exception and except is used to handle exceptions when an exception is caught.
- The exception that is raised in the above code is NameError Exception.
Also learn: Standard Exceptions In Python
We can consider another example:
class A(Exception): pass class C(A): pass try: raise A except A as e: print("This is a First User defined Exception!") try: raise C except C as e1: print("User defined Exception 2")
As a result of the above code, we get the Output as:
This is a First User defined Exception! User defined Exception 2
- In the above code, class A inherits the class Exception, class C inherits class A.
- Then raise A is used to raise exceptions that are present in A and are handled by first except block.
- Then raise C is used to raise exceptions that are present in C and are handled by nested block present in first except block.
For further reference, please refer Handling Exceptions using try and except in Python 3.x. or earlier