C++
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().
Exercise 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; }.
Show example solution
#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;
}
Test yourself
-
How is the what() method of a custom exception declared?
- const char* what() const noexcept override
- string what()
- void what()
- int what()
Show answer
int what() — what() returns const char* with override.
-
Fill in the blank: class derivation
class InvalidScore : ____ std::exception {
};
Show answer
class InvalidScore : public std::exception {
};
-
Match each expression with its purpose
- class InvalidScore
- custom type definition
- public std::exception
- base class
- override
- overrides a method
Next lesson: catch all