User-Defined Exception in Python
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” similar to the naming of the standard exceptions in python. For example,
Python3
# A python program to create user-defined exception # class MyError is derived from super class Exception class MyError(Exception): # Constructor or Initializer def __init__( self , value): self .value = value # __str__ is to print() the value def __str__( self ): return ( repr ( self .value)) try : raise (MyError( 3 * 2 )) # Value of Exception is stored in error except MyError as error: print ( 'A New Exception occurred: ' , error.value) |
Output
A New Exception occurred: 6
User-defined Exceptions in Python with Examples
Prerequisite: This article is an extension to Exception Handling.
In this article, we will try to cover How to Define Custom Exceptions in Python with Examples.
Example:
class CustomError(Exception): pass raise CustomError("Example of Custom Exceptions in Python") Output: CustomError: Example of Custom Exceptions in Python
Python throws errors and exceptions when the code goes wrong, which may cause the program to stop abruptly. Python also provides an exception handling method with the help of try-except. Some of the standard exceptions which are most frequent include IndexError, ImportError, IOError, ZeroDivisionError, TypeError, and FileNotFoundError.