why asynchronous events can not be handled using C ++ exceptions? - c++

I was reading thinking in c++ (exceptional handling).
I didn't understand following line
C++ exceptions cannot be used to handle asynchronous events because the exception and its handler are on the same call stack.
I tried searching over web but couldn't able to under stand this line.(specially call stack part)
Can anyone help on it?
EDIT:
what does same call stack means?

Exceptions, when thrown, divert the current thread's execution path to the handling of that exception. There's no way to avoid this by, say, getting another thread to perform the exception handling. The stack is important here because the exception handling involves stack-unwinding which isn't conducive to asyncronouis event handling, or much else.

The problem is like so
try {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// do some really long running operation here
longFunctionToCalculate42();
// oops, some critical error!
throw std::runtime_error( "Something went wrong!" );
});
} catch ( const std::exception& e ) {
// this won't do what you think it does
std::cerr << e.what() << std::endl;
}
The asynchronous block is executed separately from the call site, and the caller of that asynchronous function (the dispatched block) cannot catch the exception thrown from it.

You actually can handle async events using exceptions. Weather or not you should is another matter. I'll only address that briefly: you usually shouldn't because there are more purpose-direct mechanisms to handle such things. Like passing messages between threads or raising some kind of event.
As to how you can accomplish this, what you have to do is catch the exception in the throw-ing thread, record the information somewhere, and have the other thread pick that up. Note that this really boils down fundamentally to passing messages between threads, with the additional complexity of stack unwinding and the like.
C++11 provides current_exception(), returning a exception_ptr, which provides the means to save the information about the exception somewhere the responding thread can pick it up. It is still up to you to build the code that actually retrieves and processes this exception_ptr up from wherever you saved it, and that's beyond the scope of this answer.
Note when thinking about this that, unless you need actual exceptions, doing this gains you nothing over simply passing messages between threads, and costs you the stack unwinding and semantic implications of throwing and catching exceptions.

It means that asynchronous events do not follow the exception's model where "exception and its handler are on the same call stack". That is -
exceptions rely on the dynamic chain of function calls on the program
s runtime stack (they have dynamic scope ), whereas asynchronous
events must be handled by completely separate code that is not part of
the normal program flow (typically, interrupt service routines or
event loops)
Note "completely separate code", which means that you'd have to rely on some other mechanism to handle asynchronous events (if you really need so).

Related

Is there a way not to kill an Qt application which throwed a std::bad_alloc?

Exception safety is really important in Modern C++.
There is already a great question about exception safety here.
So I am not talking about Exception safety in general. I am really talking about exception safety with Qt in C++. There is also a question about Qt Exception safety on Stack Overflow and we have the Qt documentation.
After reading everything I could find about exception safety with Qt, I really feel like it is very hard to achieve exception safety with Qt. As a result I am not going to throw any kind of exceptions myself.
The real problem is with std::bad_alloc:
The Qt documentation states that Throwing an exception from a slot invoked by Qt's signal-slot connection mechanism is considered undefined behaviour, unless it is handled within the slot.
As far as I know, any slot in Qt could throw a std::bad_alloc.
It seems to me that the only reasonable option is to exit the application before the std::bad_alloc is thrown (I really do not want to go into undefined behavior land).
A way to achieve this would be to overload operator new and:
if an allocation failure occures in the GUI thread: exit (kill) the application.
if an allocation failure occures in another thread just throw a std::bad_alloc.
Before writing that operator new I would really appreciate some feedback.
Is it a good idea ?
Will my code be exception safe this way ?
Is it even possible to write exception safe code with Qt ?
This problem has been long solved and has an idiomatic solution in Qt.
All slot calls ultimately originate either from:
an event handler, e.g.:
A timer's timeout signal results from the QTimer handling a QTimerEvent.
A queued slot call results from the QObejct handling a QMetaCallEvent.
code you have full control over, e.g.:
When you emit a signal in the implementation of main, or from QThread::run, or from QRunnable::run.
An event handler in an object is always reached through QCoreApplication::notify. So, all you have to do is to subclass the application class and reimplement the notify method.
This does affect all signal-slot calls that originate from event handlers. Specifically:
all signals and their directly attached slots that originated from event handlers
This adds a per-event cost, not a per-signal cost, and not per-slot cost. Why is the difference important? Many controls emit multiple signals per a single event. An QPushButton, reacting to a QMouseEvent, can emit clicked(bool), pressed() or released(), and toggled(bool), all from the same event. In spite of multiple signals being emitted, notify was called only once.
all queued slot calls and method invocations
They are implemented by dispatching a QMetaCallEvent to the receiver object. The call is executed by QObject::event. Since event delivery is involved, notify is used. The cost is per-call-invocation (thus it is per-slot). This cost can be easily mitigated, if desired (see implementation).
If you're emitting a signal not from an event handler - say, from inside of your main function, and the slot is directly connected, then this method of handling things obviously won't work, you have to wrap the signal emission in a try/catch block.
Since QCoreApplication::notify is called for each and every delivered event, the only overhead of this method is the cost of the try/catch block and the base implementation's method call. The latter is small.
The former can be mitigated by only wrapping the notification on marked objects. This would need to be done at no cost to the object size, and without involving a lookup in an auxiliary data structure. Any of those extra costs would exceed the cost of a try/catch block with no thrown exception.
The "mark" would need to come from the object itself. There's a possibility there: QObject::d_ptr->unused. Alas, this is not so, since that member is not initialized in the object's constructor, so we can't depend on it being zeroed out. A solution using such a mark would require a small change to Qt proper (addition of unused = 0; line to QObjectPrivate::QObjectPrivate).
Code:
template <typename BaseApp> class SafeNotifyApp : public BaseApp {
bool m_wrapMetaCalls;
public:
SafeNotifyApp(int & argc, char ** argv) :
BaseApp(argc, argv), m_wrapMetaCalls(false) {}
void setWrapMetaCalls(bool w) { m_wrapMetaCalls = w; }
bool doesWrapMetaCalls() const { return m_wrapMetaCalls; }
bool notify(QObject * receiver, QEvent * e) Q_DECL_OVERRIDE {
if (! m_wrapMetaCalls && e->type() == QEvent::MetaCall) {
// This test is presumed to have a lower cost than the try-catch
return BaseApp::notify(receiver, e);
}
try {
return BaseApp::notify(receiver, e);
}
catch (const std::bad_alloc&) {
// do something clever
}
}
};
int main(int argc, char ** argv) {
SafeNotifyApp<QApplication> a(argc, argv);
...
}
Note that I completely ignore whether it makes any sense, in any particular situation, to handle std::bad_alloc. Merely handling it does not equal exception safety.
You don't need something as complex as overloading operator new. Create a class ExceptionGuard whose destructor checks std::uncaught_exception. Create this object in each slot, with automatic duration, outside any try-catch block. If there's an exception that still escapes, you can call std::terminate just before you'd otherwise return to Qt.
The big benefit is that you can place it in just the slots, not every random call to new. The big downside is that you can forget to use it.
BTW, it's not strictly necessary to call std::terminate. I'd still advice to do so in ExceptionGuard because it's intended as a last resort. It can do application-specific cleanup. If you have cleanup behavior specific to the slot you'd better do that outside ExceptionGuard, in a regular catch block.
Is it a good idea ?
It's unnecessary and needlessly complex. There are a lot of problems with trying to handle std::bad_alloc:
when it is thrown, there typically isn't much you can do about it. You're out of memory, anything you try to do might easily fail again.
in many environments, out-of-memory situations might occur without this exception being thrown. When you call new the OS just reserves a part of your (huge, 64-bit) address space. It doesn't get mapped to memory until much later, when you try to use it. If you're out of memory, then that is the step that will fail, and the OS won't signal that by throwing a C++ exception (it can't, because all you tried to do was read or write a memory address). It generates an access violation/segfault instead. This is the standard behavior on Linux.
it adds complexity to a situation that might already be tricky to diagnose and debug. Keep it simple, so that if it happens, your code won't do anything too unexpected that ends up hiding the problem or preventing you from seeing what went wrong.
Generally speaking, the best way to handle out-of-memory situations is just to do nothing, and let them take down the application.
Will my code be exception safe this way ?
Qt frequently calls new itself. I don't know if they use the nothrow variant internally, but you'd have to investigate that.
Is it even possible to write exception safe code with Qt ?
Yes. You can use exceptions in your code, you just have to catch them before they propagate across signal/slot boundaries.

Unblock synchronous read on boost::asio::serial_port

I have a boost::thread which performs synchronous reads on a boost::asio::serial_port. When I destroy an instance of the class which contains both, I want the thread to end gracefully even if its blocked in a read call. How can I do this?
Looking at the docs, I tried cancel, but it works only for asynchronous reads/writes. Then I tried close, but I got an exception and it wasn't the kind you can recover from. Perhaps using send_break or native_handle? (this is Windows and portability's not critical)
Update: I also tried to stop the io_service I passed to the serial port object's constructor, but the read wasn't unblocked.
Edit: The exception is actually "catchable", but I'd hate to put a try/catch block inside a destructor, and refactoring the code to do the shutdown process outside the destructor would trigger lots of changes in upper layers. So I'd only go for this solution if some Boost authority says there is no other way.
There is no way to unblock the synchronous read as you ask to.
There are two options:
close/shutdown the port and catch an exception, which was raised
use asynchronous reads and cancel them, when you shutdown your application
The first one, of course, is not a good idea, because you cannot distinguish terminating application from error.
On close, you say that you get an exception that 'wasn't the kind you can recover from'.
What does this mean?
The solution seems to be to catch the exception. Why cannot you do that?
For the case when you want to distinguish between an error and program termination, set a flag on program termination before the close. In the exception handler ( catch ) check the flag. If set, handle as program termination, else handle as error.
You say that you do not wish to place a try/catch block inside a destructor. This seems like an odd prejudice to me, but OK there are other ways.
You can allow the exception to propagate all the way to the topmost catch block that surrounds all your code, and handle it there. ( You do have such a try/catch block protecting your entire application, of course :-)
Other ways are also possible ... but boss just dropped by

Will main() catch exceptions thrown from threads?

I have a pretty large application that dynamically loads shared objects and executes code in the shared object. As a precaution, I put a try/catch around almost everything in main. I created a catch for 3 things: myException (an in house exception), std::exception, and ... (catch all exceptions).
As part of the shared objects execution, many pthreads are created. When a thread throws an exception, it is not caught by main. Is this the standard behavior? How can I catch all exceptions, no matter what thread they are thrown from?
Will main() catch exceptions thrown from threads?
No
When a thread throws an exception, it is not caught by main. Is this the standard behavior?
Yes, this is standard behaviour.
To catch an exception originating in thread X, you have to have the try-catch clause in thread X (for example, around everything in the thread function, similarly to what you already do in main).
For a related question, see How can I propagate exceptions between threads?
Your question is asking for something that isn't conceptually possible.
Try blocks are defined as dynamic constructs of the stack. A try block catches exceptions thrown by code reached dynamically, by call, from its contents.
When you create a new thread, you create a brand-new stack, that is not at all part of the dynamic context of the try block, even if the call to pthread_create is inside the try.
No, main will not catch exceptions thrown from other threads. You would need to use a non-standard, platform specific facility that addresses unhandled exceptions in order to aggregate the handling the way you are describing.
When I build such applications, I make sure each active object has its own top-level exception handling block, precisely to prevent the entire application from exploding if one thread fails. Using a platform-specific catch all I think begs for your overall code / solution to be sloppy. I would not use such a thing.
Consider that throwing an exception unwinds the stack. Each thread has its own stack. You will have to place a try/catch block in each thread function (i.e. in the entry point of each thread).

When is a C++ terminate handler the Right Thing(TM)?

The C++ standard provides the std::set_terminate function which lets you specify what function std::terminate should actually call. std::terminate should only get called in dire circumstances, and sure enough the situations the standard describes for when it's called are dire (e.g. an uncaught exception). When std::terminate does get called the situation seems analagous to being out of memory -- there's not really much you can sensibly do.
I've read that it can be used to make sure resources are freed -- but for the majority of resources this should be handled automatically by the OS when the process exits (e.g. file handles). Theoretically I can see a case for if say, you needed to send a server a specific message when exiting due to a crash. But the majority of the time the OS handling should be sufficient.
When is using a terminate handler the Right Thing(TM)?
Update: People interested in what can be done with custom terminate handlers might find this non-portable trick useful.
This is just optimistic:
but for the majority of resources this should be handled automatically by the OS when the process exits
About the only resources that the OS handles automatically are "File Handles" and "Memory" (And this may vary across OS's).
Practically all other resources (and if somebody has a list of resources that are automatically handled by OS's I
would love that) need to be manually released by the OS.
Your best bet is to avoid exit using terminate() and try a controlled shut down by forcing the stack to unwind correctly.
This will make sure that all destructors are called correctly and your resources are released (via destructors).
About the only thing I would do is log the problem. So that when it does happened I could go back and fix the code so that it does not happen again. I like my code to unwind the stack nicely for resource deallocation, but this is an opinion some people like abrupt halts when things go badly.
My list of when terminate is called:
In general it is called when the exception handling mechanism cannot find a handler for a thrown exception. Some specific examples are:
An exception escapes main()
Note: It is implementation defined whether the stack is unwound here.
Thus I always catch in main and then rethrow (if I do not explicitly handle).
That way I guarantee unwinding of the stack (across all platforms) and still get the benefits of the OS exception handling mechanism.
Two exceptions propagating simultaneously.
An exception escapes a desatructor while another exception is propagating.
The expression being thrown generates an exception
An exception before or after main.
If an exception escapes the constructor/destructor of a global object.
If an exception escapes the destructor of a function static variable.
(ie be careful with constructors/destructors of nonlocal static object)
An exception escapes a function registered with atexit().
A rethrow when no exception is currently propagating.
An unlisted exception escapes a method/function that has exception specifier list.
via unexpected.
Similar to a statement made in Martin York's answer, about the only thing I do in a custom terminate handler is log the problem so I can identify and correct the offending code. This is the only instance I find that using a custom terminate handler is the Right Thing.
Since it is implementation-defined whether or not the stack is unwound before std::terminate() is called, I sometimes add code to generate a backtrace in order to locate an uncaught exception1.
1) This seems to work for me when using GCC on Linux platforms.
I think the right question would be how to avoid the calls to terminate handler, rather than when to use it.

Is there an occasion where using catch all clause : catch (...) is justified?

Each time I have seen the catch all statement:
try
{
// some code
}
catch (...)
{
}
it has always been an abuse.
The arguments against using cache all clauses are obvious. It will catch anything including OS generated exceptions such as access violations.
Since the exception handler can't know what it's dealing with, in most cases the exceptions will manifest as obscure log messages or some incoherent message box.
So catch(...) seems inherently evil.
But it is still implemented in C++ and other languages (Java, C#) implements similar mechanisms. So is there some cases when its usage is justified?
(1) It's not true that the statement will catch OS exceptions. Your use of the term "Access Violation" betrays a Windows background; it was true for older MSVC++ versions.
(2) Regardsless, the catch-all behavior is useful for threads with specific purposes. Catching the failure allows the thread to report it failed. Without it, the other parts of the program need to deal with the possibility of a thread just disappearing. It also allows you to log which thread failed, and the arguments used to start the thread.
The case where it's justified in general is when you log the exception (or do something similar) or do some cleanup, and then immediately rethrow.
In C++ in particular, logging in a catch(...) block is pretty pointless since you don't have any way to obtain the exception, and cleanup is pointless because you should be using RAII for that. Using it in destructors seems to be about the only legitimate case.
the arguments against using cache all clauses are obvious , it will catch anything including OS generated exceptions such as access violation. since the exception handler can't know what its dealing with, in most cases the exceptions will manifest as obscure log message or some incoherent message box.
And if those same exceptions aren't caught you get... an incoherent message box.
catch(...) lets me at least present my own message box (and invoke custom logging, save a crash dump, etc.).
I think there are also reasonable uses of catch(...) in destructors. Destructors can't throw--well, I mean, they can throw, but if a destructor throws during stack unwinding due to an in-progress exception the program terminates, so they should not ever allow exceptions to escape. It is in general better to allow the first exception to continue to be unwound than to terminate the program.
Another situation is in a worker thread that can run arbitrary functions; generally you don't want an unceremonious crash if the task throws an exception. A catch(...) in the worker thread provides the opportunity for semi-orderly clean-up and shutdown.
In addition to what other posters have already said, I'd like to mention one nice point from the C++ Standard:
If no matching handler is found in a
program, the function std::terminate()
is called; whether or not the stack is
unwound before this call to
std::terminate() is
implementation-deļ¬ned.
(15.3/9)
This means that main() and every thread function must be wrapped in a catch-all handler; otherwise, one can't even be sure that destructors for automatic objects will be called if an uncaught exception is thrown.
try {...} catch (...) is needed around body of callback function which is called from code
that doesn't understand C++ exceptions (usually C library).
Otherwise, if some C++ library you use throws an exception that doesn't derive from
std::exception, it will probably cause calling code to crash or corrupt its internal state.
Instead you should catch this exception and either finish program immediately or
return some error code (meaning "we are doomed and I don't know why", but it's still better
then letting C++ exception to pass through).
Around thread procedure. Mostly because of the same reason as 1.
And because otherwise thread failure would pass unnoticed.
catch(...) has been useful for me in two circumstances, both of which are unjustified (I can't even remember the second)
The first is my overall application safety. While throwing exceptions that don't derive from std::exception is a No-No, I have one just in case in my main() function:
int execute(void); // real program lies here
int main(void)
{
try
{
return execute();
}
catch(const std::exception& e)
{
// or similar
std::cerr << "Unhandled exception: " << e.what() << std::endl;
return EXIT_FAILURE;
}
catch(...)
{
std::cerr << "Unknown exception!" << std::endl;
return EXIT_FAILURE;
}
}
Now, it's only there "just in case", and it's not really justified. There should be no reason to ever enter that catch clause, as that would mean somebody has done a Bad Thing. Observe how useless the statement really is; "Something bad happened, no clue what!" It's only a step above just crashing in the first place.
The second use might be in destructors or some other function that needs to do manual management before letting the exception propagate. That's not really a justification either, as things should clean themselves up safely with RAII. But I may have used it once or twice for some reason I can't recall, and I can't see a reason to ever do so again.
catch (...) allows you to write code in which you can legitimately claim a guarantee that your code will not crash even when you are not in long term complete control of the submodules your code depends on. Your claim is tantamount to claiming that this semantic cannot be used except as a means of abuse. Maybe so, but military specifications may differ from you on this issue.
catch(...) is necessary in the absence of the finally clause as found in other languages:
try {
...
} catch(...) {
cleanup...
throw;
}
The alternative - making stack objects to 'own' everything - is often much more code and less readable and maintainable. The platform API is often C, and does not come with it conveniently bundled.
It is also useful around plugin code that you do not control or simply do not trust from a stability perspective. It won't stop them crashing, but it might keep things a little saner.
Finally, there are times when you really do not care about the outcome of something.