Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ exception class with printf style string?

Tags:

c++

c++11

In C++11, is there an easy (or even better, built-in) way to do something like this to do printf-style strings in an exception?

throw std::runtime_error( "Failed to open '%s' [%d]: %s", 
         filename, errno, strerror(errno) );

I know I could snprintf to a `char []' then pass the result into an exception constructor with or w/o converting to std::string first.

Just wondering if C++11 has anything better/simpler to offer.

like image 687
Brian McFarland Avatar asked Sep 11 '15 17:09

Brian McFarland


People also ask

Can printf print string?

C++ printf is a formatting function that is used to print a string to stdout. The basic idea to call printf in C++ is to provide a string of characters that need to be printed as it is in the program.

Can printf throw exception?

printf() is a C function and therefore cannot and does not throw C++ exceptions; that is why a C++ style try/catch won't help.

What is %B in printf?

The Printf module API details the type conversion flags, among them: %B: convert a boolean argument to the string true or false %b: convert a boolean argument (deprecated; do not use in new programs).

How do you use sprintf strings?

Syntax: int sprintf(char *str, const char *string,...); Return: If successful, it returns the total number of characters written excluding null-character appended in the string, in case of failure a negative number is returned .


1 Answers

Since C++11, you can construct exceptions from an std::string:

std::runtime_error("Failed to open " + std::string(filename) + std::to_string(errno));

This has the slight drawback that the constructor of std::string might throw and thus terminate your program. However, this should only come into play while handling some kind of "out of memory" exception.

like image 170
Baum mit Augen Avatar answered Oct 08 '22 00:10

Baum mit Augen