问题
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 NSNotification
s. However, this solution seems a little corky because it's basically reimplementing the @catch clause given different types of NSException
s as a parameter. I wanted to check if any other solutions are available.
回答1:
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.
来源:https://stackoverflow.com/questions/8859777/can-i-catch-exceptions-thrown-from-one-thread-in-another-thread-in-objective-c