How to Create Custom Exception in C++: Syntax and Example
In C++, you create a custom exception by defining a new class that inherits from
std::exception or another standard exception class. Override the what() method to provide a custom error message. Then throw an object of this class when an error occurs.Syntax
To create a custom exception, define a class that inherits from std::exception. Override the what() method to return a descriptive error message. This method should return a const char* and be marked noexcept.
- class CustomException : Your new exception class.
- public std::exception : Inherits standard exception behavior.
- const char* what() const noexcept override : Returns error message.
cpp
class CustomException : public std::exception { public: const char* what() const noexcept override { return "Custom error occurred"; } };
Example
This example shows how to define a custom exception class and use it in a try-catch block. When the exception is thrown, the catch block prints the custom error message.
cpp
#include <iostream> #include <exception> class CustomException : public std::exception { public: const char* what() const noexcept override { return "Custom error occurred"; } }; int main() { try { throw CustomException(); } catch (const std::exception& e) { std::cout << "Caught exception: " << e.what() << std::endl; } return 0; }
Output
Caught exception: Custom error occurred
Common Pitfalls
- Not inheriting from
std::exceptioncan make your exception incompatible with standard catch blocks. - Forgetting to mark
what()asnoexceptcan cause unexpected behavior. - Returning a temporary string or non-const pointer from
what()leads to undefined behavior. - Throwing exceptions by pointer instead of by value is discouraged.
cpp
/* Wrong way: what() returns std::string (temporary) */ class BadException : public std::exception { public: std::string what() const noexcept override { // wrong return type return "Bad error"; } }; /* Right way: what() returns const char* and is noexcept */ class GoodException : public std::exception { public: const char* what() const noexcept override { return "Good error"; } };
Quick Reference
- Inherit from
std::exceptionfor compatibility. - Override
const char* what() const noexceptto provide error message. - Throw exceptions by value and catch by reference.
- Keep error messages simple and static to avoid lifetime issues.
Key Takeaways
Create custom exceptions by inheriting from std::exception and overriding what() method.
Mark what() as noexcept and return a const char* string literal or static message.
Throw exceptions by value and catch them by const reference for best practice.
Avoid returning temporary strings or non-const pointers from what() to prevent errors.
Custom exceptions improve error clarity and integrate well with standard C++ error handling.