Skip to content

User-defined exception in Python example

  • by

User-defined exceptions need to be derived (either directly or indirectly) from the built-in Exception class in the Python example.

class CustomError(Exception):
    ...
    pass

try:
   ...

except CustomError:
    ...

User-defined exception in Python example

A simple example code creates a user-defined exception class MyError is derived from the 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("Custom Error"))

    # Value of Exception is stored in error
except MyError as error:
    print('A New Exception occurred: ', error.value)

Output:

User-defined exception in Python example
# class MyError is extended from super class Exception
class User_Error(Exception):
   # Constructor method
   def __init__(self, value):
      self.value = value
   # __str__ display function
   def __str__(self):
      return(repr(self.value))
try:
   raise(User_Error("User defined error"))
   # Value of Exception is stored in error
except User_Error as error:
   print('A New Exception occured:',error.value)

Do comment if you have any doubts or suggestions on this Python exception-handling topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading