Define a custom exception class that takes a string message as an attribute

Question:

Define a custom exception class that takes a string message as an attribute

Hints:

  • To define a custom exception, we need to define a class inherited from the Exception.

Solution:

class MyError(Exception):
    """My own exception class

    Attributes:
        msg  -- explanation of the error
    """

    def __init__(self, msg):
        self.msg = msg

error = MyError("something wrong")

Leave a Comment