1
votes

Is it possible to catch an exception thrown from one thread in another thread? For example, I am spawning a thread from my main thread. The spawned thread may throw uncaught exceptions. Is it possible to have the spawning thread catch these exceptions?

One solution would be to catch the exceptions from the entry point of the spawned thread and "handle" the exception by posting an NSNotification. Then, the spawning thread can listen for these NSNotifications. However, this solution seems a little corky because it's basically reimplementing the @catch clause given different types of NSExceptions as a parameter. I wanted to check if any other solutions are available.

1
Note that exceptions are only used to indicate unrecoverable errors in iOS/Mac OS X. If you are using exceptions for anything recoverable, you are doing it wrong.bbum
Using exceptions only for unrecoverable errors is a convention and is not wrong per se. There are 3 common objections to using exceptions (a) they perform poorly in Obj-C (b) resource leaking (b2) memory leaking. (a) is mitigated if you only use them in exceptional circumstance - which you should anyway, (b) must be handled in exception-based design independent of language, and handling (b2) (a subset of (b)) is assisted by garbage collection, ARC in Obj-C++, or ARC in Obj-C with -fobjc-arc-exceptions. So if you using exceptions right you're not "doing it wrong". For your Q see @Seva.CRD
@bbum These are "unrecoverable" situations.Raffi Khatchadourian
@CRD Take a look at the latest exception documentation. It seems that there are performance improvements for 64-bit applications. Nevertheless, performance shouldn't be a huge issue for exceptions, they are supposed to be used for exceptional situations, implying that these situations don't occur often.Raffi Khatchadourian
@RaffiKhatchadourian Good -- I was just making sure.bbum

1 Answers

3
votes

It's impossible and pointless. The throwing thread has no way of knowing if the spawning thread is currently running within a try block. If not, what would it do? Defer throwing until the spawner cares to catch? What if it never does?

Consider another scenario. And exception is thrown in the worker thread while the spawner thread is doing something and happens to be in inconsistent state - say, it's in the middle of updating some data structure. The exception would break the flow of execution and leave the data in said inconsistent state. Not to mention that whatever otherwise good task that the spawner was doing would remain forever incomplete.

So the right way to go about it is catching in the top level of the worker thread and passing to the spawner thread using something like [NSObject performSelector:]. The general idea that the spawner should be notified about the booboos in the spawnee(s) is solid, but throwing spawnee's exceptions to the spawner is not right. Note - I said "throwing", as opposed to passing by other mechanisms that Cocoa offers.