简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM