C++ User-Defined Exceptions

Exception handling is an essential aspect of any programming language, including C++. It allows developers to handle and manage unexpected or exceptional situations that may occur during the execution of a program. While C++ provides built-in exceptions like std::exception, it also allows developers to define their own custom exceptions to handle specific scenarios.

Why Use User-Defined Exceptions?

Using user-defined exceptions in C++ can greatly enhance the clarity and maintainability of your code. By creating custom exceptions, you can provide more specific information about the nature of the error or exceptional condition that has occurred. This helps in better understanding the cause of the exception and enables more precise error handling.

Creating a User-Defined Exception

In C++, creating a user-defined exception involves defining a new class that inherits from the base exception class, std::exception. Let’s consider an example where we want to create a custom exception for handling out-of-range errors in a program:


#include <exception>
#include <string>

class OutOfRangeException : public std::exception
{
public:
    OutOfRangeException(const std::string& message) : errorMessage(message) {}

    const char* what() const noexcept override
    {
        return errorMessage.c_str();
    }

private:
    std::string errorMessage;
};

In the above example, we have defined a new class called OutOfRangeException that inherits from std::exception. The class has a constructor that takes a string message as a parameter, which will be used to store the error message associated with the exception. The what() function is overridden to provide a custom error message when the exception is thrown.

Throwing and Catching User-Defined Exceptions

Once we have defined our custom exception, we can throw it using the throw keyword when a specific exceptional condition occurs. In the following example, we demonstrate how to throw and catch the OutOfRangeException:


#include <iostream>

int main()
{
    try
    {
        int value = 10;
        int maxValue = 5;

        if (value > maxValue)
        {
            throw OutOfRangeException("Value is out of range.");
        }
    }
    catch (const OutOfRangeException& ex)
    {
        std::cout << "Exception caught: " << ex.what() << std::endl;
    }

    return 0;
}

In the above code snippet, we have a simple if condition that checks if the value is greater than the maximum allowed value. If the condition is true, we throw the OutOfRangeException with a custom error message. The exception is then caught in the catch block, where we can handle or display the error message as per our requirements.

Handling Multiple User-Defined Exceptions

C++ allows us to define multiple custom exceptions to handle different exceptional scenarios. By creating specific exception classes for different types of errors, we can have more granular control over the exception handling process. Here’s an example that demonstrates the usage of multiple user-defined exceptions:


class DivideByZeroException : public std::exception
{
public:
    const char* what() const noexcept override
    {
        return "Divide by zero exception.";
    }
};

int divide(int dividend, int divisor)
{
    if (divisor == 0)
    {
        throw DivideByZeroException();
    }

    return dividend / divisor;
}

int main()
{
    try
    {
        int result = divide(10, 0);
    }
    catch (const DivideByZeroException& ex)
    {
        std::cout << "Exception caught: " << ex.what() << std::endl;
    }

    return 0;
}

In the above example, we have defined a new exception class called DivideByZeroException to handle the scenario of dividing a number by zero. The divide() function throws this exception when the divisor is zero. The exception is then caught in the catch block, where we can handle the error gracefully.

Conclusion

User-defined exceptions in C++ provide a powerful mechanism for handling specific exceptional situations in a program. By creating custom exception classes, developers can improve the clarity and maintainability of their code. These exceptions allow for more precise error handling and provide valuable information about the nature of the exception. By understanding the process of creating, throwing, and catching user-defined exceptions, developers can effectively handle exceptional scenarios in their C++ programs.

Scroll to Top