How should I write an efficient exception class to show the error that can be prevented by fixing the source code mistakes before run-time?
This is the reason I chose std::invalid_argument.
My exception class(not working, obviously):
class Foo_Exception : public std::invalid_argument
{
private:
std::string Exception_Msg;
public:
explicit Foo_Exception( const std::string& what_arg );
virtual const char* what( ) const throw( );
};
explicit Foo_Exception::Foo_Exception( const std::string& what_arg ) // how should I write this function???
{
Exception_Msg.reserve( 130000 );
Exception_Msg = "A string literal to be appended, ";
Exception_Msg += std::to_string( /* a constexpr int */ );
Exception_Msg += /* a char from a const unordered_set<char> */;
}
const char* Foo_Exception::what( ) const throw( )
{
return Exception_Msg.c_str( );
}
An if block that throws Foo_Exception:
void setCharacter( const char& c )
{
if ( /* an invalid character (c) is passed to setCharacter */ )
{
try
{
const Foo_Exception foo_exc;
throw foo_exc;
}
catch( const Foo_Exception& e )
{
std::cerr << e.what( );
return;
}
}
/*
rest of the code
*/
}
int main( )
{
setCharacter( '-' ); // dash is not acceptable!
return 0;
}
As you can see, I need to concatenate Exception_Msg with a few substrings in order to form the completed message. These substrings are not only string literals but also constexpr ints and chars from a static std::unordered_set<char>. That's why I used std::string because it has the string::operator+= which is easy to work with. And needless to say, my goal is to reduce heap allocations down to only 1.
Another very important question is that where should I place the handler( the try-catch )? Inside the main() wrapping the setCharacter() or keep it inside setCharacter?
Please make a good and standard custom exception class similar to the above. Or write your own. Thanks in advance.