Editor settings

General settings

Save settings

Learn to program with Python

Creating custom error classes #

Sometimes in your program, the build-in error classes in Python, such as TypeError or ZeroDivisionError, may not be suitable for our needs. In such cases, you can create custom error classes to represent specific types of exceptions that occur in your code. By defining custom error classes, you can provide more descriptive and meaningful error messages.

All we need to do to create our own error is create a class that inherits from the built-in Exception class.

class MyOwnError(Exception):
    pass

Now that we have our own error class, we can raise the error just like any other errors.

raise MyOwnError("My custom error message")

### Output
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    raise MyOwnError("My custom error message")
__main__.MyOwnError: My custom error message

Exercise #

  • Create your own error class named BadFunctionCallError.

Tests #

  • BadFunctionCallError should inherit from Exception
Output will be displayed here