Saturday, 8 October 2022

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

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?



from Why and how the exception in any thread crashes the whole app in Android

No comments:

Post a Comment