What is the preferred way to include error messages in C++?

It is all a matter of preference with both benefits and downfalls.

Hard-coding string literals at the site of the error may be harder to maintain but it also is easier to read in my honest opinion.

for example

cout << "You were unable to login. "
     << "Please check you're user name and password and try again"
     << endl;

shows intent a lot better than

cout << LOGIN_CREDENTIALS_ERROR << endl;

However, the plus sides of not hard-coding the message (both 2 and 3):

//Foo.cpp:
cout << DIVIDE_BY_ZERO_ERROR << endl;

//Bar.cpp
cout << DIVIDE_BY_ZERO_ERROR << endl;

// If you want to change DIVIDE_BY_ZERO_ERROR text you only have to do it once
//ErrorMessages.h (Ops grammar needs correcting)
const std:string DIVIDE_BY_ZERO_ERROR = "Dont not divide by zero";

Also, if the error messages are subject to change:

// ErrorMessages.h
#ifdef LOCALIZATION_EN
const std:string FRIENDLY_ERROR = "Hello, you are doing something wrong";
#elseif LOCALIZATION_FR
const std:string FRIENDLY_ERROR = "Bonjour, ...";
...

OR

// ErrorMessages.h
#ifdef DEBUG
const std:string SOME_ERROR = "More detailed error information for developers"
#else
const std:string SOME_ERROR = "Human friendly error message"
#endif

Leave a Comment