0
0
Pythonprogramming~5 mins

Creating exception classes in Python

Choose your learning style9 modes available
Introduction

Sometimes, you want to make your own special errors to explain problems clearly in your program.

When you want to show a specific problem that normal errors don't explain well.
When you want to catch and handle a certain type of error differently.
When you want to add extra information to an error to help fix it.
When you want your program to be easier to understand and maintain.
Syntax
Python
class MyError(Exception):
    pass

You create a new error by making a class that uses Exception as its base.

The pass means the new error acts like a normal error unless you add more code.

Examples
This makes a simple new error called MyError.
Python
class MyError(Exception):
    pass
This error stores a message and shows it when printed.
Python
class ValueTooSmallError(Exception):
    def __init__(self, message):
        self.message = message
    def __str__(self):
        return f"ValueTooSmallError: {self.message}"
This error remembers the wrong number and explains why it is wrong.
Python
class NegativeNumberError(Exception):
    def __init__(self, number):
        self.number = number
    def __str__(self):
        return f"NegativeNumberError: {self.number} is not allowed"
Sample Program

This program makes a new error called MyError. It checks if a number is negative. If yes, it raises the error with a message. The try block runs the check. If the error happens, the except block catches it and prints the message.

Python
class MyError(Exception):
    pass

def check_number(x):
    if x < 0:
        raise MyError("Negative numbers are not allowed")
    else:
        print(f"{x} is okay")

try:
    check_number(5)
    check_number(-3)
except MyError as e:
    print(f"Caught an error: {e}")
OutputSuccess
Important Notes

You can add extra details to your error by adding methods or properties.

Use raise to create your error when a problem happens.

Catch your error with except YourErrorName as e to handle it nicely.

Summary

Create your own errors by making classes that inherit from Exception.

Use raise to trigger your custom error when needed.

Catch and handle your custom errors with try-except blocks.