Answers for "how to define a new error in python"

1

how to define a new error in python

# https://www.programiz.com/python-programming/user-defined-exception

class SimpleCustomError(Exception): # it is a simple example.
  pass

class CustomError(Exception):

    # We can override the constructor of Exception class to accomplish our own __init__.
    def __init__(self,number, customMessage:str = 'The number should not be more than 1 and less than -1.'):
        self.number = number
        self.msg = customMessage
        super(CustomError, self).__init__(self.msg)

    # We can implement our custom __str__ dunder method.
    def __str__(self):
        return '%s is out of range. %s' % (self.number, self.msg)

def run(num):
    if num > 1 or num < -1:
        raise CustomError(num)


try:
    run(2)
except CustomError as err:
    print(err.msg)
    print(err)
    print(str(err))
else:
    print('No Error occurred.')
finally:
    print('End of run.')
Posted by: Guest on September-27-2021

Code answers related to "how to define a new error in python"

Python Answers by Framework

Browse Popular Code Answers by Language