Can I call a method before my application go to crash
Asked Answered
C

5

5

I'm a newbie in android and I always see Exception when I'm running my code. So, somebody can tell me Can I call a method before app go to crash anywhere without "try-catch".

Cierracig answered 13/11, 2013 at 4:37 Comment(5)
can you post some code and stack trace please?Carnify
In general, no. See the documentation here: docs.oracle.com/javase/tutorial/essential/exceptions/…Goodhumored
Depends what kind of exception is it if you want to detect beforehand whether it will fail ?Neckerchief
yes you can do it by implementing UncaughtExceptionHandlerAlleneallentown
better u should fix your code..plz post code and logcatIcon
L
13

This would be better way to handle uncaught exception:

public class MyApplication extends Application {
@Override
    public void onCreate() {
        super.onCreate();
        appInitialization();
    }

    private void appInitialization() {
         defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
         Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
    }

    private UncaughtExceptionHandler defaultUEH;

    // handler listener
    private Thread.UncaughtExceptionHandler _unCaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            ex.printStackTrace();
            // TODO handle exception here
        }
    };
}

Application is a Base class for those who need to maintain global application state. And hence here, it will be a better place to handle such exceptions.

EDIT: The above code will handle uncaught exceptions if they are thrown inside UI thread. If an exception has occurred in worker thread, you can handle it in following way:

private boolean isUIThread(){
        return Looper.getMainLooper().getThread() == Thread.currentThread();
    }
// Setup handler for uncaught exceptions.
    Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler()
    {
        @Override
        public void uncaughtException (Thread thread, Throwable e)
        {
            handleUncaughtException (thread, e);
        }
    });

    public void handleUncaughtException(Thread thread, Throwable e) {
        e.printStackTrace(); // not all Android versions will print the stack trace automatically

        if (isUIThread()) {
            // exception occurred from UI thread
            invokeSomeActivity();

        } else {  //handle non UI thread throw uncaught exception

            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    invokeSomeActivity();
                }
            });
        }
    }
Lyse answered 13/11, 2013 at 5:0 Comment(6)
oh my god using this one I can trace unexpected force close in my app..This will be very usefullIcon
But If I implement this in application class my application stop crashingShavers
this is good. i had a question on multi- threading. wont this only work on the main thread ? because your calling Thread.setDefaultUncaughtExceptionHandler so i think its getting the current thread only. please advise if i am wrong and how to handle multi thread if i am correctToinette
Hi @Toinette good point. The earlier code snippet will throw exception on in case exception is thrown from a UI thread. To handle worker thread case as well, updated code snippet should work. Thank you for addressing this. :)Lyse
hi @ Shrikant i just did a test although in android and it seems your initial code snippet does not on all threads. i threw an exception on a child thread and the call back for uncaughtException was invoked. FYI. i was having a big issue with this so i wrote a answer to it here but it involves crashlytics for anyone who needs it to work with crashlytics check here: #42261390Toinette
@Shrikant your answer is THE SHIT. Thanks for this great piece of code.Medicable
C
0

I think what you search is the UncaughtExceptionHandler. It is notified whenever an Exception is fired and not catched on its way bubbling up through your application.

See http://www.intertech.com/Blog/android-handling-the-unexpected/ for more details on implementing this in android.

Cardiovascular answered 13/11, 2013 at 4:42 Comment(0)
A
0

Try this way

1) create class

import android.content.Context;
import android.content.Intent;
import android.os.Process;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.Thread.UncaughtExceptionHandler;

public class CrashReportHandler implements UncaughtExceptionHandler {

    public static void attach(Context context) {
        Thread.setDefaultUncaughtExceptionHandler(
                new CrashReportHandler(context)
        );
    }

    ///////////////////////////////////////////// implementation

    private CrashReportHandler(Context context) {
        m_context = context;
    }

    public void uncaughtException(Thread thread, Throwable exception) {
        StringWriter stackTrace = new StringWriter();
        exception.printStackTrace(new PrintWriter(stackTrace));

        //You will get call back here when app crashes.

        // from RuntimeInit.crash()
        Process.killProcess(Process.myPid());
        System.exit(10);
    }

    private Context m_context;

}

How to use this class?

write this line in your activity onCreate() method

CrashReportHandler.attach(this);
Alleneallentown answered 13/11, 2013 at 4:49 Comment(2)
But if every activity is registering this class then there will definitely be a memory leak when activity is finished. The CrashReportHandler will contain reference of each activity even if that activity is finished.Lyse
My question is instead of doing Process.killProcess(Process.myPid()); System.exit(10); is it possible to throw the exception again ?What i am trying to do is record the exception in another log file and then i want the app to crash as usual ? if i throw the exception again in uncaughtException method will it be a infinite loop ?Toinette
A
0


There is method called Uncaught exception which is called just before force close dialog , you can write ur piece of code there .. Please check Using Global Exception Handling on android

Accomplice answered 13/11, 2013 at 4:52 Comment(1)
If you use settings / force close, the process is terminated and the code does not execute.Chickabiddy
S
-1

Use CrashLytics for crash reporter free of cost and easy to implement

https://www.crashlytics.com/

Serviceberry answered 13/11, 2013 at 5:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.