Catch all possible exceptions for Android globally and reload the application

I know that the best way to prevent system crashes is to catch all possible exceptions in different ways. Therefore, I use try try blocks anywhere in my code. However, as you know, sometimes you forget to test some scenarios that cause some unplanned exceptions, and the user receives the message "Unfortunately, the application has stopped working ...". This is bad for any application. Unfortunately, the people who will use my application are not native English speakers, so they also will not understand the error message.

So, I want to know whether it is possible to catch all possible exceptions globally (using one try catch block in some main classes, and not in all classes and methods !!!) and restart the application automatically and without any strange messages? Or at least is it possible to change the crash message ?

Thank you

+7
source share
4 answers

In your onCreate

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
                //Catch your exception
                // Without System.exit() this will not work.
                System.exit(2);
            }
        });
+12
source

So, I want to know if global detection of all possible exceptions is possible ... and restart the application automatically

.. , , , , .

; , .

, , - , -, . UncaughtExceptionHandler onCreate(), , , , UncaughtExceptionHandler. , .

, - . try catch , .

, . , , . try-catch ,

  • , try-catch rethrow ;
  • (runtime) . - Integer.parseInt(), NumberFormatException , .

, ,

. .

, , , , .

? , , . crashmessage (, logcat), . , . , - , . - .

+4

:

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread paramThread, Throwable paramThrowable) {

        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(getActivity(),"Your message", Toast.LENGTH_LONG).show();
                Looper.loop();
            }
        }.start();
        try
        {
            Thread.sleep(4000); // Let the Toast display before app will get shutdown
        }
        catch (InterruptedException e) {    }
        System.exit(2);
    }
});
+1

You can handle uncaught exceptions using the FireCrasher library , recover from it, and send user feedback as a dialog or message.

You can learn more about the library in this middle article.

0
source

All Articles