how to define a new error in python

Solutions on MaxInterview for how to define a new error in python by the best coders in the world

showing results for - "how to define a new error in python"
Noemi
17 Jan 2019
1# https://www.programiz.com/python-programming/user-defined-exception
2
3class SimpleCustomError(Exception): # it is a simple example.
4  pass
5
6class CustomError(Exception):
7
8    # We can override the constructor of Exception class to accomplish our own __init__.
9    def __init__(self,number, customMessage:str = 'The number should not be more than 1 and less than -1.'):
10        self.number = number
11        self.msg = customMessage
12        super(CustomError, self).__init__(self.msg)
13
14    # We can implement our custom __str__ dunder method.
15    def __str__(self):
16        return '%s is out of range. %s' % (self.number, self.msg)
17
18def run(num):
19    if num > 1 or num < -1:
20        raise CustomError(num)
21
22
23try:
24    run(2)
25except CustomError as err:
26    print(err.msg)
27    print(err)
28    print(str(err))
29else:
30    print('No Error occurred.')
31finally:
32    print('End of run.')
33