Exceptions: throw, try and catch

Exception Class Hierarchy

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

Abstract art representing computer programming

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 {
  explicit MyException(const std::string& message)
    : message_(message) {}

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

  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.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved