Is there a way to catch or handle EXC_BAD_ACCESS?

风流意气都作罢 提交于 2019-11-27 03:47:58

问题


As far as I understand, EXC_BAD_ACCESS happens when you try to access bad memory (feel free to correct me if I'm wrong)?

Is there a way to kind of catch it like in a try-catch in Java to prevent total app failure?


回答1:


Nope; EXC_BAD_ACCESS means things have gone wildly off the rails. Your program is trying to access a memory address that is invalid. I.e. memory has been corrupted and there is no predictable recovery.

It may be a memory management issue. If you can reproduce the issue, turn on NSZombies and see what happens. Or post the backtrace here.

Note that try-catch style exceptions are non-recoverable in iOS/Cocoa, too. Exceptions are not to be used for recoverable error handling. That is what NSError is for.




回答2:


You can sometimes catch it in main, with a signal handler. Doesn't allow you to do much, though, other than maybe log some stuff.




回答3:


A new C library SignalRecovery can enable programs to recover from operating system exceptions such as EXC_BAD_ACCESS. It can be used in IOS/MacOS/Linux.

Sample code:

signal_try(label) {
    // Add your code need try.
    int* ptr = NULL;
    *ptr = 0;
}
signal_catch(label) {
    // Add your code to process exceptions, or do nothing.
    siginfo_t* info = signal_info();
}
signal_end(label)
// Continue run



回答4:


A try catch can be used but you'll first need to know what caused the issue. You can enable NSZombie for your current build to catch the error and eliminate the need. Edit current scheme, enable NSZombie.

  • Update * Swift2+ has excellent error handling now and is definitely worth checking out. Swift Error Handling


来源:https://stackoverflow.com/questions/16202029/is-there-a-way-to-catch-or-handle-exc-bad-access

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