Example for User-defined Exception in Python

How do you write a user-defined exception in Python?

Here’s an example of how you can define and use a user-defined exception in Python:

class InvalidInputError(Exception):
    """Exception raised for invalid input."""

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

def divide_numbers(a, b):
    if b == 0:
        raise InvalidInputError("Cannot divide by zero.")
    return a / b

# Example usage
    result = divide_numbers(10, 0)
except InvalidInputError as e:
    print("Error:", e.message)

In this example, we define a custom exception called InvalidInputError that inherits from the base Exception class. The exception is raised in the divide_numbers function when the denominator b is zero. When the exception is raised, an error message is passed to the exception’s constructor.

In the example usage, we try to divide 10 by 0, which is an invalid operation. The InvalidInputError exception is raised, and we catch it using a try-except block. The error message is then printed to the console.

By creating custom exceptions, you can provide more specific and meaningful error messages for different scenarios in your code.

What is user-defined exception and built in exception in Python?

In Python, both user-defined exceptions and built-in exceptions are used to handle and manage errors and exceptional situations in a program.

User-defined exceptions:

These are exceptions that you define yourself by creating a new class. You can create custom exceptions to handle specific errors or exceptional conditions that are relevant to your program. User-defined exceptions are useful when you need to differentiate between different types of errors or provide more specific information about the cause of an exception. You can define your own exception classes by inheriting from the built-in Exception class or any of its subclasses.

Here’s an example of a user-defined exception:

class InvalidInputError(Exception):
    """Exception raised for invalid input."""

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

Built-in exceptions:

These are exceptions that are already defined in the Python language and are available for use without requiring any additional code. Python provides a wide range of built-in exceptions that cover common error scenarios. Some of the commonly used built-in exceptions include ValueError, TypeError, IndexError, KeyError, FileNotFoundError, and ZeroDivisionError, among others. These exceptions are raised when certain predefined errors occur during the execution of a program.

Here’s an example of using a built-in exception:

    result = 10 / 0
except ZeroDivisionError:
    print("Error: Division by zero.")

In this example, the built-in ZeroDivisionError exception is raised when attempting to divide a number by zero.

Both user-defined exceptions and built-in exceptions are used in error handling to ensure that your program can gracefully handle exceptional situations and provide appropriate feedback or take necessary actions.

Read More;

  • Dmytro Iliushko

    I am a middle python software engineer with a bachelor's degree in Software Engineering from Kharkiv National Aerospace University. My expertise lies in Python, Django, Flask, Docker, REST API, Odoo development, relational databases, and web development. I am passionate about creating efficient and scalable software solutions that drive innovation in the industry.

Leave a Comment