任何线程中的异常为什么以及如何在安卓系统中崩溃整个应用程序



如果我在活动中生成一个线程并抛出类似的异常

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Thread {
throw java.lang.RuntimeException()
}.start()
}

这将使应用程序崩溃,出现致命错误

如果我在纯Java程序中执行等效操作,那么主线程将继续运行。例如:

public class ThreadTest {
public static void main(String args[]) {
System.out.println("Start ");
new Thread(){
public void run() {
System.out.println("Inner Start");
throw new RuntimeException();
}
}.start();
try{
Thread.sleep(3000);
System.out.println("End");
}catch(Exception ignored){ }
}
}

输出将是

Start 
Inner Start
Exception in thread "Thread-0" java.lang.RuntimeException
at ThreadTest$1.run(ThreadTest.java:17)
End

是什么导致了这种行为上的差异?

因为Android运行时实际上会杀死你的Android应用程序。Java和Android代码的行为都完全符合Java语言规范,该规范规定:

If no catch clause that can handle an exception can be found, 
then the **current thread** (the thread that encountered the exception) is terminated

然而,在关于程序终止的部分中,它也指出:

A program terminates all its activity and exits when one of two things happens:
* All the threads that are not daemon threads terminate.
* Some thread invokes the exit method of class Runtime or class System, and the exit operation is not forbidden by the security manager.

虽然这可能会让人觉得安卓系统的实现不符合要求,但事实并非如此。JLS说,如果所有线程都被终止,它就必须终止,但它没有说"终止";一个不同的进程如果检测到一个线程被终止就不能终止程序";,而Android运行时,它不是JVM,是一个不同的进程,可以在检测到异常时终止该进程。请注意,这种行为在本机Android代码中与Android文档中所述的类似:

* An app that is written using Java or Kotlin crashes
if it throws an unhandled exception, represented by the Throwable class.
* An app that is written using native-code languages crashes 
if there’s an unhandled signal, such as SIGSEGV, during its execution.

相关内容

最新更新