Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Which of the following alternatives would be preferred?

  1. Include the error message within code wherever needed:

    cout << "I am an error message!" <<endl;
    exit(-1);
    
  2. Define the error messages in a separate header file:

    #include "ErrorMessages.h"
    cout << ERRORMESSAGE_1 <<endl;
    exit(-1);
    
  3. Create a function that contains the error messages.

Also is it common to include unique error IDs as part of these messages?

like image 853
polerto Avatar asked May 26 '13 18:05

polerto


2 Answers

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
like image 71
Tom Fobear Avatar answered Oct 09 '22 09:10

Tom Fobear


It depends upon if you have localization requirements for your application. If you do, you want all your strings in one place, including error messages. If you don't have requirements like that, I prefer to put the messages inline (your first example). That way, if I want to find the code that's complaining, I can just grep the message.

like image 43
lurker Avatar answered Oct 09 '22 09:10

lurker