Python Tutorial

Python Variable

Python Operators

Python Sequence

Python String

Python Flow Control

Python Functions

Python Class and Object

Python Class Members (properties and methods)

Python Exception Handling

Python Modules

Python File Operations (I/O)

How to create and use custom exception in Python

In Python, you can create custom exceptions by defining a new class that inherits from the built-in Exception class or one of its subclasses. Custom exceptions can be useful for providing more specific error information and making your code more readable and maintainable.

Here's a step-by-step guide on how to create and use custom exceptions in Python:

  • Define a custom exception class: Create a new class that inherits from the Exception class or one of its subclasses (e.g., ValueError, TypeError, etc.). You can add a custom __init__ method to pass additional information to the exception.
class MyCustomError(Exception):
    def __init__(self, message):
        self.message = message
        super().__init__(self.message)
  • Raise the custom exception in your code: Use the raise keyword followed by the custom exception class with any required arguments.
def divide(a, b):
    if b == 0:
        raise MyCustomError("Division by zero is not allowed")
    return a / b
  • Handle the custom exception using try and except: Wrap the code that may raise the custom exception in a try block and handle the exception in an except block.
try:
    result = divide(10, 0)
except MyCustomError as e:
    print(f"An error occurred: {e}")
else:
    print(f"The result is: {result}")

In this example, the divide() function raises a MyCustomError exception when trying to divide by zero. The try and except blocks handle the custom exception, printing an error message instead of allowing the program to crash.

By creating and using custom exceptions, you can make your code more readable, maintainable, and informative, providing better error messages and easier error handling.

  1. Creating user-defined exceptions in Python:

    User-defined exceptions allow you to create custom error conditions specific to your application.

    class CustomError(Exception):
        pass
    
  2. How to define a custom exception class in Python:

    class MyCustomException(Exception):
        def __init__(self, message="Default custom exception message"):
            self.message = message
            super().__init__(self.message)
    
  3. Raising custom exceptions in Python code:

    def example_function(value):
        if value < 0:
            raise MyCustomException("Value must be non-negative")
        # Rest of the code...
    
  4. Inheriting from built-in exceptions for custom exceptions in Python:

    class ValueTooHighError(ValueError):
        pass
    
    def validate_value(value):
        if value > 100:
            raise ValueTooHighError("Value exceeds maximum limit")
    
  5. Adding custom messages to exceptions in Python:

    class CustomError(Exception):
        def __init__(self, value, message="Default custom error"):
            self.value = value
            self.message = message
            super().__init__(self.message)
    
    raise CustomError(42, "Custom error message")
    
  6. Handling custom exceptions in try-except blocks:

    try:
        # Some code that may raise a custom exception
        raise CustomError("Custom exception occurred")
    except CustomError as ce:
        print(f"Caught custom exception: {ce}")
    
  7. Creating a custom exception hierarchy in Python:

    class BaseCustomError(Exception):
        pass
    
    class SubCustomError(BaseCustomError):
        pass
    
    try:
        raise SubCustomError("Sub-custom exception occurred")
    except BaseCustomError as bce:
        print(f"Caught base custom exception: {bce}")
    
  8. Logging custom exceptions in Python:

    import logging
    
    try:
        raise MyCustomException("Custom exception for logging")
    except MyCustomException as mce:
        logging.error(f"Caught custom exception: {mce}")
    
  9. Implementing error codes with custom exceptions in Python:

    class ErrorCodeException(Exception):
        def __init__(self, error_code, message="Default error message"):
            self.error_code = error_code
            self.message = message
            super().__init__(self.message)
    
    try:
        raise ErrorCodeException(404, "Resource not found")
    except ErrorCodeException as ece:
        print(f"Error code: {ece.error_code}, Message: {ece}")
    
  10. Using custom exceptions in Python frameworks:

    Custom exceptions can be integrated into various frameworks for consistent error handling.

    from flask import Flask, abort
    
    app = Flask(__name__)
    
    @app.route('/')
    def example_route():
        try:
            # Some code that may raise a custom exception
            raise MyCustomException("Custom exception in Flask route")
        except MyCustomException as mce:
            return str(mce), 500