I would like to throw an exception when my C++ methods encounter something weird and can't recover. Is it OK to throw a std::string
pointer?
Here's what I was looking forward to doing:
void Foo::Bar() { if(!QueryPerformanceTimer(&m_baz)) { throw new std::string("it's the end of the world!"); } } void Foo::Caller() { try { this->Bar(); // should throw } catch(std::string *caught) { // not quite sure the syntax is OK here... std::cout << "Got " << caught << std::endl; } }
Can shrinking a std::string throw an exception? The question is whether this function can throw an exception. Can the call to resize throw an exception when used to make a string smaller? And the answer appears to be yes, at least in C++17.
C++ exception handling is built upon three keywords: try, catch, and throw. throw − A program throws an exception when a problem shows up. This is done using a throw keyword. catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem.
You need to catch it with char const* instead of char* . Neither anything like std::string nor char* will catch it. Catching has restricted rules with regard to what types it match.
Exception handling is used to handle the exceptions. We can use try catch block to protect the code. Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions.
Yes. std::exception
is the base exception class in the C++ standard library. You may want to avoid using strings as exception classes because they themselves can throw an exception during use. If that happens, then where will you be?
boost has an excellent document on good style for exceptions and error handling. It's worth a read.
A few principles:
you have a std::exception base class, you should have your exceptions derive from it. That way general exception handler still have some information.
Don't throw pointers but object, that way memory is handled for you.
Example:
struct MyException : public std::exception { std::string s; MyException(std::string ss) : s(ss) {} ~MyException() throw () {} // Updated const char* what() const throw() { return s.c_str(); } };
And then use it in your code:
void Foo::Bar(){ if(!QueryPerformanceTimer(&m_baz)){ throw MyException("it's the end of the world!"); } } void Foo::Caller(){ try{ this->Bar();// should throw }catch(MyException& caught){ std::cout<<"Got "<<caught.what()<<std::endl; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With