C++ how to get handle to exception thrown in generic catch handler - c++

Is there any way to get handle to exception thrown inside generic catch block.
try
{
throw ;
}
catch(...)
{
// how to get handle to exception thrown
}
Thanks

You can use std::current_exception.
Rearranging from cppreference:
#include <string>
#include <exception>
#include <stdexcept>
int main()
{
eptr;
try {
std::string().at(1); // this generates an std::out_of_range
} catch(...) {
std::exception_ptr eptr = std::current_exception(); // capture
}
}
Inside the catch(...) block, the current exception has been captured by the exception_ptr eptr. The exception object referenced by an std::exception_ptr remains valid as long as there remains at least one std::exception_ptr that is referencing it: std::exception_ptr is a shared-ownership smart pointer.

The problem is that is C++, an exception is allowed to be of any type and not only a subclass of std::exception. That's the reason why the common idiom is to use only exception classes derived from std::exception to have a coherent interface.
You can always as suggested by #PaoloM use std::current_exception(). But it has some limitations that make it hard to use, because to be allowed to represent any type of exception it is a std::exception_ptr that only can (ref. in cpluscplus.com):
be default-constructed (acquiring a null-pointer value).
be copied, including being copied a null-pointer value (or nullptr).
be compared against another exception_ptr object (or nullptr) using either operator== or operator!=, where two null-pointers are always considered equivalent, and two non-null pointers are considered equivalent only if they refer to the same exception object.
be contextually convertible to bool, as false if having null-pointer value, and as true otherwise.
be swapped, and being destructed.
Performing any other operation on the object (such as dereferencing it), if at all supported by the library implementation, causes undefined behavior.
If you want to be able to to serious things with an exception, you should use dedicated exception handlers:
try
{
throw ;
}
catch (MyException& a) {
// Ok, it is a know type and I know how to deal with it
}
catch (std::exception& e) {
// it is a subclass of std::exception, I can at least use its what() method
catch(...)
{
// I can get a std::exception_ptr from current_exception, but cannot know what to do with it
}

Related

Copy std::exception object to a struct member in C++ [duplicate]

I have an API which internally has some exceptions for error reporting. The basic structure is that it has a root exception object which inherits from std::exception, then it will throw some subclass of that.
Since catching an exception thrown in one library or thread and catching it in another can lead to undefined behavior (at least Qt complains about it and disallows it in many contexts). I would like to wrap the library calls in functions which will return a status code, and if an exception occurred, a copy of the exception object.
What is the best way to store an exception (with it's polymorphic behavior) for later use? I believe that the c++0x future API makes use of something like this. So what is the best approach?
The best I can think of is to have a clone() method in each exception class which will return a pointer to an exception of the same type. But that's not very generic and doesn't deal with standard exceptions at all.
Any thoughts?
EDIT: It seems that c++0x will have a mechanism for this. It is described as "library magic". Does that mean that is doesn't require any of the language features of c++0x? if not, are there any implementations which are compatible with c++03?
EDIT: Looks like boost has an implementation of exception copying. I'll keep the question open for any non boost::copy_exception answers.
EDIT: To address j_random_hacker's concerns about the root cause of the exception being an out of memory error. For this particular library and set of exceptions, this is not the case. All exceptions derived from the root exception object represent different types of parsing errors caused by invalid user input. Memory related exceptions will simply cause a std::bad_alloc to be thrown which is addressed separately.
As of C++11, this can be done using std::exception_ptr.
(I use this in a class that makes an std::thread interruptible provided that the underlying thread implementation is a POSIX thread. To handle exceptions that may be thrown in the user's code - which causes problems if they are thrown in a certain critical section of my implementation - I store the exception using std::exception_ptr, then throw it later once the critical section has completed.)
To store the exception, you catch it and store it in the ptr variable.
std::exception_ptr eptr;
try {
... do whatever ...
} catch (...) {
eptr = std::current_exception();
}
You can then pass eptr around wherever you like, even into other threads (according to the docs - I haven't tried that myself). When it is time to use (i.e. throw) it again, you would do the following:
if (eptr) {
std::rethrow_exception(eptr);
}
If you want to examine the exception, you would simply catch it.
try {
if (eptr) {
std::rethrow_exception(eptr);
}
} catch (const std::exception& e) {
... examine e ...
} catch (...) {
... handle any non-standard exceptions ...
}
You have what would be what I think is your best, only answer. You can't keep a reference to the original exception because it's going to leave scope. You simply have to make a copy of it and the only generic way to do that is with a prototype function like clone().
Sorry.
You're allowed to throw anything, including pointers. You could always do something like this:
throw new MyException(args);
And then in the exception handler store the caught pointer, which will be fully polymorphic (below assuming that MyException derives from std::exception):
try {
doSomething(); // Might throw MyException*
} catch (std::exception* pEx) {
// store pEx pointer
}
You just have to be careful about memory leaks when you do it this way, which is why throw-by-value and catch-by-reference is normally used.
More about catch-by-pointer: http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.8
The reason why catching an exception thrown in one library and catching it in another can lead to undefined behavior is that these libraries could be linked with different Runtime libraries. If you will return exception from a function instead of throwing it you will not avoid that problem.
My utility library has an AnyException class that is basically the same as boost::any without the casting support. Instead, it has a Throw() member that throws the original object stored.
struct AnyException {
template<typename E>
AnyException(const E& e)
: instance(new Exception<E>(e))
{ }
void Throw() const {
instance->Throw();
}
private:
struct ExceptionBase {
virtual void Throw() const =0;
virtual ~ExceptionBase() { }
};
template<typename E>
struct Exception : ExceptionBase {
Exception(const E& e)
: instance(e)
{ }
void Throw() const {
throw std::move(instance);
}
private:
E instance;
};
ExceptionBase* instance;
};
This is a simplification, but that's the basic framework. My actual code disables copying, and has move semantics instead. If needed, you can add a virtual Clone method to the ExceptionBase easily enough... since Exception knows the original type of the object, it can forward the request onto the actual copy constructor, and you immediately have support for all copiable types, not just ones with their own Clone method.
When this was designed, it was not meant for storing caught exceptions... once an exception was thrown, it propagated as normal, so out-of-memory conditions were not considered. However, I imagine you could add an instance of std::bad_alloc to the object, and store it directly in those situations.
struct AnyException {
template<typename E>
AnyException(const E& e) {
try {
instance.excep = new Exception<E>(e);
has_exception = true;
} catch(std::bad_alloc& bad) {
instance.bad_alloc = bad;
bas_exception = false;
}
}
//for the case where we are given a bad_alloc to begin with... no point in even trying
AnyException(const std::bad_alloc& bad) {
instance.bad_alloc = bad;
has_exception = false;
}
void Throw() const {
if(has_exception)
instance.excep->Throw();
throw instance.bad_alloc;
}
private:
union {
ExceptionBase* excep;
std::bad_alloc bad_alloc;
} instance;
bool has_exception;
};
I haven't actually tested that second bit at all... I might be missing something glaringly obvious that will prevent it from working.

Is destroying the last std::exception_ptr pointing to an exception after calling std::rethrow_exception portable?

I have a portability question concerning the lifetime of exception. In the code below, an exception is thrown in one thread (mySlave) and transferred to another thread (myMaster) using a std::exception_ptr. myMaster is always waiting for different events via a std::condition_variable. An exception in mySlave is such an event. In the predicate function of the wait in myMaster, I check if the exception pointer is null. If an exception has been thrown in mySlave, I copy the exception pointer to a temporary variable in myMaster, set the original exception pointer to null and rethrow it in myMaster. This way, the original exception pointer is ready to serve in the predicate function once the program has recovered from the exception.
This works fine with VC14, but the final software is likely to be ported to other platforms in the future. In my code, all exception_ptr references to the exception will run out of scope after the rethrow, thus the original exception will be destroyed. My concern is if std::rethrow_exception is guaranteed to always generate a copy of the exception when rethrowing it, or if it could also use a reference to the exception, causing it to be no longer valid when I try to catch if in myMaster?
#include <mutex>
#include <thread>
#include <atomic>
#include <exception>
#include <iostream>
#include <memory>
class SomeClass
{
public:
/*...*/
void MaseterFunction();
void SlaveFunction();
private:
/*...*/
std::mutex mutex_gotEvent;
std::condition_variable condVar_gotEvent;
std::exception_ptr slaveLoopException;
/*...*/
std::atomic<bool> running = true;
};
class MyException : public std::runtime_error
{
public:
MyException() : std::runtime_error("Ooops") {}
};
void SomeClass::SlaveFunction()
{
try
{
throw MyException();
}catch(const std::exception& e)
{
std::unique_lock<std::mutex> lock(mutex_gotEvent);
slaveLoopException = std::current_exception();
condVar_gotEvent.notify_all();
}
}
void SomeClass::MaseterFunction()
{
while (running)
{
try
{
{
/*Wait for something interesting to happen*/
std::unique_lock<std::mutex> lock(mutex_gotEvent);
condVar_gotEvent.wait(lock, [=]()->bool {
return !(slaveLoopException == nullptr); // Real code waits for several events
});
}
/*Care for events*/
/*...*/
if (slaveLoopException)
{
std::exception_ptr temp_ptr = slaveLoopException;
slaveLoopException = nullptr;
std::rethrow_exception(temp_ptr);
}
}
catch (const MyException& e)
{
std::cout << e.what();
running = false;
}
}
}
int main()
{
std::shared_ptr<SomeClass> someClass = std::make_shared<SomeClass>();
std::thread myMaster([someClass]() {someClass->MaseterFunction(); });
std::thread mySlave([someClass]() {someClass->SlaveFunction(); });
std::cin.ignore();
if (myMaster.joinable())
{
myMaster.join();
}
if (mySlave.joinable())
{
mySlave.join();
}
return 0;
}
I thought about declaring temp_ptr at class level or use a std::atomic<bool> variable in addition to the exception pointer to be used in the predicate function. However both of these solutions would keep the exception alive after it is no longer used, which seem not very elegant to me. It would also be possible to set the exception pointer to null in each catch block in myMaster, but I think that this is likely to introduce bugs when new exceptions are added later on and the programmer forgets to null the exception pointer.
EDIT:
I found the following statements on this subject:
Statement 1:
The exception object referenced by an std::exception_ptr remains valid
as long as there remains at least one std::exception_ptr that is
referencing it
Statement 2:
The VS implementation of rethrow_exception appears to make a copy of
the exception. Clang and gcc do not make copies.
Statement 3
The exception object is destroyed after either the last remaining
active handler for the exception exits by any means other than
rethrowing, or the last object of type std::exception_ptr (§18.8.5)
that refers to the exception object is destroyed, whichever is later.
From (1) I would expect the exception to be destroyed too early. From (2) I would expect this to be of no effect when using VC as a copy is used anyway. From 3, I can't tell if this could save me when using gcc or clang. I mean, the exit takes place by rethrowing, but it is not rethrown from a handler. Is the new handler already considered active when the temporary pointer is destroyed or is the pointer destroyed first and with it the exception, leaving the follow up catch blocks with an invalid exception reference?
CppRef states that rethrow_exception -- Throws the previously captured exception object. I haven't checked the standard myself (but see below), but:
Speculation
It seems likely to me that from the point onwards where you rethrow the exception, exception handling is "back to normal", i.e. it is the job of the implementation to keep the thrown object around, and the language doesn't care whether you threw via a normal throwor via a rethrow_exception.
Stated differently: The exception_ptr needs to be valid at the point of rethrow_exception, after this, the thrown exception is the same as any other and whether or not it shares with the original exception pointer shouldn't matter.
OP provided a good link with a standard quote:
4/ The memory for the exception object is allocated in an unspecified way, except as noted in §3.7.4.1. If a handler exits by rethrowing, control is passed to another handler for the same exception. The exception object is destroyed after either the last remaining active handler for the exception exits by any means other than rethrowing, or the last object of type std::exception_ptr (§18.8.5) that refers to the exception object is destroyed, whichever is later. In the former case, the destruction occurs when the handler exits, immediately after the destruction of the object declared in the exception-declaration in the handler, if any. In the latter case, the destruction occurs before the destructor of std::exception_ptr returns. The implementation may then deallocate the memory for the exception object; any such deallocation is done in an unspecified way. [ Note: a thrown exception does not propagate to other threads unless caught, stored, and rethrown using appropriate library functions; see §18.8.5 and §30.6. —end note ]
Which seems to imply what I wrote above: The exception object lives as long as necessary: the whichever is later part of the quote seems to explicitly call this out.
Update: I missed that OP doesn't re-throw from the handler, so I am also unsure what is supposed to happen here.
I do believe that after rethrow_exception the (new) exception in flight should be treated as-if it was generated by a normal throw expression - anything else makes little sense.
The way I speculate here is that even prior to std::exception_ptr every implementation had an internal mechanism that was similar to std::exception_ptr in that it had to keep the thrown exception object (copy or not) alive outside of normal stack frames until it was no longer needed by any handler up the stack. So I can speculate that clang or gcc would not do a copy, but instead hold an "internal exception_ptr" as soon as you invoke throw/rethrow_exception.

Is is possible in C++ to throw nothing?

Under exceptional circumstances, I want my program to stop processing, output an error to std::cerr, clean up, and exit.
However, calling exit() will not call all the destructors of any objects that have been constructed. I would like to have the destructors called nicely, so I wrapped all the code in a try-catch block, something like this:
int main(int argc, char** argv){
try {
bool something_is_not_right = false;
/* lots of variables declared here */
/* some code that might set something_is_not_right to true goes here */
if(something_is_not_right){
std::cerr << "something is not right!!!" << std::endl;
throw '\0'; // dummy unused variable for throwing.
}
}
catch (...) {}
return 0;
}
In this way, I get guaranteed destruction of all my variables. But I can't seem to find a way to get C++ to throw nothing. throw; has a special meaning in C++; it isn't throwing nothing.
Is there a way to throw nothing?
No
It's not possible to throw nothing. You need to throw something. While you may have seen people use the throw keyword without anything, this just means they are re-throwing the currently handled exception.
This is not a direct answer to your question, but a personal recommendation.
You might want to take a look at the predefined exceptions of stdexcept which cover almost any exceptional behaviour that occurs in a program. In your case I would throw a std::runtime_error. Also, only catch what you expect to be thrown and not catch 'em all. If you really want to catch everything, then catch std::exception (the base class of all standard exceptions).
In my opinion handling unknown exceptions doesn't really make sense and the only logical consequence is to just abort execution.
#include <iostream>
#include <stdexcept>
int main()
{
try
{
bool something_is_not_right = true;
if ( something_is_not_right )
throw std::runtime_error("something is not right!!!");
}
catch (std::runtime_error& e)
{
std::cerr << e.what() << '\n';
throw;
}
}
How do you know that the reason for the catch is your error or something else (out of memory is always a good one). If you detect an error, then you should create and throw the reason for that error in a custom exception. Then in main, you can tell the difference between your detected error and something you didn't expect. It's just good practice.
Well you "can" but it doesn't throw nothing. It terminates.
5.17 Throwing an exception:
Evaluating a throw-expression with an operand throws an exception (15.1)
A throw-expression with no operand rethrows the currently handled exception (15.3).
If no exception is presently being handled, evaluating a throw-expression with no operand calls std::terminate()
This is valid:
int main () {
throw;
return 0;
}
Source used: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4296.pdf
But it won't cleanup anything. std::terminate is used when the cleanups fail.
Otherwise you have to use operand, and then this section becomes relevant:
15.1 Throwing an exception [except.throw]
Throwing an exception copy-initializes (8.5, 12.8) a temporary object, called the exception object. The temporary is an lvalue and is used to initialize the variable declared in the matching handler (15.3).
So you have to pass something that is able to be initialized, which by definition cannot be nothing.
In order to ensure full cleanup you have to throw an exception and catch it somewhere. Implementations are not required to clean up stack objects when an exception is thrown but not caught. The requirement (in [except.handle]/9) when an exception is thrown but not caught is that the program calls std::terminate(), and it's implementation-defined whether stack objects are cleaned up.

Why should i use catch by reference when exception pointers are thrown

When catching an exception by reference is the only advantage that i get is avoiding a copy of the exception object being made? Basically the difference between
try
{
CString a_csSQL = _T("SELECT * FROM Library");
CDatabase aDB;
aDB.OpenEx(g_csConnectionStringWdDSN,CDatabase::noOdbcDialog));
aDB.ExecuteSQL(a_csSQL);
}
catch(CDBException *& ex)
{
ex->Delete();
}
AND
try
{
CString a_csSQL = _T("SELECT * FROM Library");
CDatabase aDB;
aDB.OpenEx(g_csConnectionStringWdDSN,CDatabase::noOdbcDialog))
aDB.ExecuteSQL(a_csSQL);
}
catch(CDBException * ex)
{
ex->Delete();
}
The difference between the two codes you posted is that the first one catches a pointer to an exception by reference, and the second one catches a pointer to an exception by value. In neither case is an exception copied, since you're dealing with pointers.
In general, exceptions should be thrown by value, and caught by reference. The C++ standard library is designed with this expectation in mind. However, older libraries, (MFC for instance) throw exceptions by pointer as you do here, and are expected to be caught by pointer.
There's no effective difference between catching a pointer by value and by reference, except that if you catch by reference that gives you the (completely useless) option of deleting the exception, allocating a new exception with that same pointer, and rethrowing the same exception-pointer.
If the exception is throw by a pointer you can avoid using reference.
References are really required if the exception is thrown by value.

std exceptions inviting unsafe usage?

It is recommended that you always throw something derived from std::exception and there are a few predefines specialisations such as std::runtime_error
std::exception's interface is given in terms of non-throwing accessors. Great. Now look at the constructor for std::runtime_error
class runtime_error : public exception {
public:
explicit runtime_error (const string &);
};
So if I do this
try {
foo ();
}
catch (...) {
throw std :: runtime_error ("bang");
}
it's entirely possible that foo threw because it's out of memory, in which case constructing the string argument to runtime_error can also throw. This would be a throw-expression which itself also throws: won't this will call std::terminate?
Doesn't this mean we should always do this instead:
namespace {
const std :: string BANG ("bang");
}
...
try {
foo ();
}
catch (...) {
throw std :: runtime_error (BANG);
}
BUT WAIT this won't work either, will it? Because runtime_error is going to copy its argument, which may also throw...
...so doesn't this mean that there is no safe way to use the standard specialisations of std::exception, and that you should always roll your own string class whose constructor only fails without throwing?
Or is there some trick I'm missing?
I think your main problem is that you are doing catch(...) and translating to a std::runtime_error thereby losing all type information from the original exception. You should just rethrow with throw().
Practically, if you are short of memory you are likely have a bad_alloc exception thrown at some point and there's not a lot else you can - or should - do. If you want to throw an exception for a reason other than an allocation failed then you are not likely to have a problem constructing a sensible exception object with meaningful contextual information. If you hit a memory issue while formatting your exception object there's not a lot you can do other than propagate the memory error.
You are right that there is a potential problem if you construct a new string object to construct an exception, but if you want to format a message with context this can't be avoided in general. Note that the standard exception objects all have a const char* constructor (as of last week) so if you have a const char* that you want to use you don't have to construct a new std::string object.
std::runtime_error must copy it's argument, but not necessarily as a new string object. There could be an area of statically allocated memory which it can the contents of its argument to. It only has to fulfil the what() requirements which only requires returning a const char *, it doesn't have to store a std::string object.
This would be a throw-expression which itself also throws: won't this
will call std::terminate?
No, it wouldn't. It would just throw the exception about insufficient memory. The control will not reach the outer throw part.
BUT WAIT this won't work either, will it? Because runtime_error is
going to copy its argument, which may also throw...
Exception classes with a throwing copy-constructors are as evil as throwing destructors. Nothing that can really be done about it.
std::runtime_error is designed to treat the usual runtime errors, not
out of memory or other such critical exceptions. The base class
std::exception does not do anything which may throw; nor does
std::bad_alloc. And obviously, remapping std::bad_alloc into an
exception which requires dynamic allocation to work is a bad idea.
The first thing is what would you want to do if you happen to have a bad_alloc exception because you're out of memory?
I'd say in a classic C++ program, you'd want to have the program somehow trying to tell you what happened and then terminates.
In a classic C++ program you'd then let the bad_alloc exception propagate to the main section of the program. The main will contain an arragement of try/catch like this:
int main()
{
try
{
// your program starts
}
catch( const std::exception & e )
{
std::cerr << "huho something happened" << e.what() << std::endl;
}
catch( ... )
{
std::cerr << "huho..err..what?" << std::endl;
}
}
you'll only use catch( ... ) inside the main and at the starting functions of threads. Contrary to some other languages like Java you're not expected to catch all possible exceptions locally. You just let them propagate until you catch them where you wanted to.
Now if you have code that specifically must check std::bad_alloc, you should only catch( const std::bad_alloc & ) locally. And there it should maybe wise to do something else rather than just rethrow another exception.
I found in The C++ Programming Language §14.10 also that the C++ exception-handling mechanism keeps a bit of memory to itself for holding exceptions, so that throwing a standard library exception will not throw an exception by itself. Of course it is possible also to let the exception-handling mechanism run out of memory if you really code something perverted.
So, to sum up, if you do nothing and let big exceptions like bad_alloc propagate nicely where you want to catch them, in my opinion you're safe. And you should not use catch( ... ) or catch(const std::exception & ) anywhere except in the main function and in the starting functions of threads.
Catching all exceptions to rethrow a single exception is really the last thing to do. You lose every advantages you got with the C++ exception-handling mechanism.