Just started playing around with SDL2 again this morning, although the fact that SDL is used in the example here is not relevant, for the purposes of this question we could consider any framework / toolkit / library which can produce runtime errors.
Started writing the following code:
if(SDL_Init(SDL_INIT_VIDEO) < 0)
{
std::cerr << SDL_GetError() << std::endl;
}
I don't think this is very good.
This style of outputting messages to
cerr
is not easy to change in future if we needed to do so. If we want to print error messages to a file instead, then we would have to find all occurances of this code snipped and changecout
to a file. This would clearly not be practical or easy.It isn't very flexible. Perhaps we might want to have errors, warnings, and general info messages. They might need to go to different places depending on how the user has configured our program. Perhaps some users want to see all warnings and info and others want to see nothing but the most "critical" error messages.
From working on other projects I have seen things used which look like macros.
For example, the following sticks in my mind:
DT_THROW_IF(condition, "message");
My assumption is that this is implemented as a macro. If condition
evaluates to true
then message
appears in the output. (cout
/cerr
)
The use of a macro like this might go some way to addressing the above issues, however I have heard that it is not good practice to make extensive uses of macros.
- What are some best practices for error message and warning message handeling in C or C++ programs? What good solutions are available and when is their use appropriate?