Home > Mobile >  When does std::format throw an exception?
When does std::format throw an exception?

Time:02-07

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::format may throw an exception. But under which circumstances?

From [format.err.report]:

Formatting functions throw format_­error if an argument fmt is passed that is not a format string for args. They propagate exceptions thrown by operations of formatter specializations 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.

  •  Tags:  
  • Related