如果我在活動中產生一個執行緒并拋出這樣的例外
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Thread {
throw java.lang.RuntimeException()
}.start()
}
這將使應用程式因 FATAL ERROR 崩潰
如果我在純 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
是什么導致了這種行為差異?
uj5u.com熱心網友回復:
因為 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.
雖然這可能會讓人覺得 Android 實作不兼容,但事實并非如此。JLS 說如果所有執行緒都終止,它必須終止,但它沒有說“如果檢測到一個執行緒終止,另一個行程不能終止程式”,以及不是 JVM 的 Android 運行時和是一個不同的行程可以在檢測到例外時終止該行程。請注意,此行為在原生 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.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/513762.html
