Home > Net >  Why and how the exception in any thread crashes the whole app in Android
Why and how the exception in any thread crashes the whole app in Android

Time:10-11

If I spawn a thread in activity and throw an exception like this

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    Thread {
        throw java.lang.RuntimeException()
    }.start()
}

This will crash the app with FATAL ERROR

If I do equivalent in a pure Java program, the main thread will continue to run. For example:

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){ }
    }
}

The output will be

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

What causes this difference in behaviour?

CodePudding user response:

Because the Android Runtime is what actually kills your Android app. Both the behavior of the Java and the Android code are perfectly compliant with the Java Language Specification, which states:

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

however, in the section about program termination it also states this:

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.

While this may make it feel like the Android implementation is non-compliant, that is isn't the case. The JLS says that it must terminate if all threads are terminated, but it doesn't say "an different process can't terminate the program if it detects that one thread is terminated", and the Android Runtime, which is not a JVM and is a different process can terminate the process when it detects an exception. Note that this behavior is similar in native Android code as Android documentation states:

* 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.
  • Related