Can I catch exceptions thrown from one thread in another thread in Objective-C?

三世轮回 提交于 2020-01-06 03:40:06

问题


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:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!