注意: 正确地使用 uncaughtException


'uncaughtException' 事件是一种粗糙的异常处理的机制,只能用作不得已的最后手段。 此事件不应该被用作相当于就算出错也继续执行。 未处理的异常本身就意味着应用程序处于未定义的状态。 尝试恢复应用程序代码而未正确地从异常中恢复,可能会导致其他无法预料和不可预测的问题。

此事件的句柄中抛出的异常不会被捕获。 进程会以非零的退出码退出,并打印堆栈跟踪。 这是为了避免无限的循环。

在出现未捕获的异常时尝试去恢复,就类似于在升级电脑时拔掉电源线。 10次中有9次不会出现问题。 但是第10次时系统就可能出现崩溃。

'uncaughtException' 事件的正确使用方式是:在进程被关闭之前,执行清理已分配资源(比如文件描述符、句柄等)的同步操作。 在 'uncaughtException' 事件触发之后,尝试恢复正常运行是不安全的。

重启已经崩溃的应用是更可靠的方式,不管 uncaughtException 事件是否被触发,应该在独立的过程中使用外部监视器,以检测应用程序故障并根据需要恢复或重启。

'uncaughtException' is a crude mechanism for exception handling intended to be used only as a last resort. The event should not be used as an equivalent to On Error Resume Next. Unhandled exceptions inherently mean that an application is in an undefined state. Attempting to resume application code without properly recovering from the exception can cause additional unforeseen and unpredictable issues.

Exceptions thrown from within the event handler will not be caught. Instead the process will exit with a non-zero exit code and the stack trace will be printed. This is to avoid infinite recursion.

Attempting to resume normally after an uncaught exception can be similar to pulling out the power cord when upgrading a computer. Nine out of ten times, nothing happens. But the tenth time, the system becomes corrupted.

The correct use of 'uncaughtException' is to perform synchronous cleanup of allocated resources (e.g. file descriptors, handles, etc) before shutting down the process. It is not safe to resume normal operation after 'uncaughtException'.

To restart a crashed application in a more reliable way, whether 'uncaughtException' is emitted or not, an external monitor should be employed in a separate process to detect application failures and recover or restart as needed.