I am using OutputDebugStringA() to output diagnostic info from my program that I can read with DbgView.
Today I am using std::stringstream to format messages:
int value = 5;
std::stringstream ss;
ss << "value=" << value;
OutputDebugStringA(ss.str().c_str());
This is rather verbose and I am looking into using std::format() instead:
int value = 5;
OutputDebugStringA(std::format("value={0}",value).c_str());
which seems nice.
My only worry is that std::format may throw an exception.
But under which circumstances?
It would be really bad if some diagnostic or error checking code I write itself throws an exception that messes up the execution of my program.
EDIT: example that throws an exception:
std::string s = std::format("value={},{}", value);
CodePudding user response:
My only worry is that
std::formatmay throw an exception. But under which circumstances?
From [format.err.report]:
Formatting functions throw
format_errorif an argumentfmtis passed that is not a format string forargs. They propagate exceptions thrown by operations offormatterspecializations and iterators. Failure to allocate storage is reported by throwing an exception as described in [res.on.exception.handling].
In short, format_error will be thrown when your format string is not valid for format arguments.
CodePudding user response:
According to cppreference:
https://en.cppreference.com/w/cpp/utility/format/format
Throws std::bad_alloc on allocation failure. Also propagates exception thrown by any formatter.
The million dollar question: when is std::bad_alloc thrown??
Again in the doc:
std::bad_alloc is the type of the object thrown as exceptions by the allocation functions to report failure to allocate storage.
