Exception Class Hierarchy

How can I create my own custom exception classes in C++?

In C++, you can create your own custom exception classes by deriving them from the standard exception class hierarchy. The std::exception class serves as the base class for all standard exceptions, and you can inherit from it to create your own specialized exception classes.

Here's an example of creating a custom exception class:

#include <iostream>
#include <exception>
#include <string>

class MyException : public std::exception {
public:
  explicit MyException(const std::string& message)
    : message_(message) {}

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

private:
  std::string message_;
};

In this example, we define a custom exception class called MyException that inherits from std::exception. The class has a constructor that takes an error message as a parameter and stores it in a private member variable.

We override the what() member function, which is a virtual function defined in the std::exception class. This function returns a C-style string (const char*) that represents the error message associated with the exception. We return the stored error message using the c_str() function of std::string.

To use the custom exception class, you can throw an instance of it using the throw keyword:

try {
  // Some code that may throw an exception
  throw MyException("Something went wrong!");
} catch (const MyException& ex) {
  std::cout << "Caught MyException: "
    << ex.what();
} catch (const std::exception& ex) {
  std::cout << "Caught std::exception: "
    << ex.what();
}

In this example, we throw an instance of MyException with a specific error message. The exception can be caught using a catch block that specifically handles MyException, or it can be caught by a more general catch block that handles std::exception, since MyException inherits from it.

By creating custom exception classes, you can provide more specific and meaningful error information in your code, making it easier to handle and diagnose exceptions.

Exceptions: throw, try and catch

This lesson provides an introduction to exceptions, detailing the use of throw, try, and catch.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Performance Impact of Exceptions
What is the performance impact of using exceptions in C++?
Exception Safety
What is exception safety, and how can I ensure my code is exception-safe?
Exception Handling Best Practices
What are some best practices for exception handling in C++?
Exception Specifications
What are exception specifications in C++, and when should I use them?
Rethrowing Exceptions
What is rethrowing an exception in C++, and when is it useful?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant