Answers for "how to create a error 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
1

catch error data with except python

import sys
try:
	S = 1/0 #Create Error
except: # catch *all* exceptions
    e = sys.exc_info()
    print(e) # (Exception Type, Exception Value, TraceBack)

############
#    OR    #
############
try:
	S = 1/0
except ZeroDivisionError as e:
    print(e) # ZeroDivisionError('division by zero')
Posted by: Guest on June-11-2020

Code answers related to "how to create a error python"

Python Answers by Framework

Browse Popular Code Answers by Language