CodeBlanks Logo Icon CodeBlanks

Custom exceptions

Learn to write your own std::exception-derived class.

Custom exception class

To define your own exception type, you write a class derived from std::exception. This is the basic way to name your application's specific errors. You override the what() method to return your custom message.

class InvalidScore : public std::exception {
public:
    const char* what() const noexcept override {
        return "invalid score";
    }
};

Here InvalidScore is derived from std::exception; the what() method returns the custom message. This way a catch (const std::exception& e) block also catches the custom exception.

Throwing a custom exception

You throw your custom exception with throw. Like standard exceptions, it is caught by an appropriate catch block. A catch (const std::exception& e) block catches both standard and custom exceptions.

if (score > 100) {
    throw InvalidScore();
}

Here, if score is greater than 100, InvalidScore is thrown. The caller can catch it with a standard catch block and read the custom message via e.what().

Practice Define the InvalidScore class

Add #include <stdexcept>. Define class InvalidScore : public std::exception. Open a public: block and write the const char* what() const noexcept override { return "invalid score"; } method. In main, add try { throw InvalidScore(); } catch (const std::exception& e) { cout << e.what() << endl; }.

Starter code

main.cpp
#include <iostream>
#include <stdexcept>
using namespace std;

// Define the InvalidScore class

int main() {
    // in try throw the class, in catch print the message
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <stdexcept>
using namespace std;

class InvalidScore : public std::exception {
public:
    const char* what() const noexcept override {
        return "invalid score";
    }
};

int main() {
    try {
        throw InvalidScore();
    } catch (const std::exception& e) {
        cout << e.what() << endl;
    }
    return 0;
}

Expected output

invalid score

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How is the what() method of a custom exception declared?

  • const char* what() const noexcept override
  • string what()
  • void what()
  • int what() Correct answer

Explanation: what() returns const char* with override.

2 Fill in the blank: class derivation

Question
class InvalidScore : ____ std::exception {
};
Answer
class InvalidScore : public std::exception {
};

Explanation: public derivation gives access to base members.

3 Match each expression with its purpose

Term Meaning
class InvalidScore custom type definition
public std::exception base class
override overrides a method

All lessons in Beginner