My question is how to catch unhandled errors in Android application and pass them further so it will indeed crash the application.
I'm creating SDK for Android and I still want developers to handle their errors but I also want to get informed about crashes of mine.
I know that to catch an error I could use:
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
}
});
But how to pass it futher? How to crash application? If I use:
throw new RuntimeException(ex);
It won't crash application but rather cause ANR error.
The second question is how does Fabric (Crashlytics) library work? Mind that I also don't want to spoil workflow of Fabric if it's also present in the application.
In a low level UncaughtExceptionHandler
is the mechanism to catch of all your application errors in case if instance of UncaughtExceptionHandler
attached to application thread.
How to crash application?
Use this thread
It won't crash application but rather cause ANR error.
This happens because you throw Exception and you going inside uncaughtException
method, where you throw exception again. So you have a cycle.
But how to pass it futher?
I suppose you need to save exception data to some storage - SD card, send crash info to email, etc.
In this case you need implement your logic inside uncaughtException
method.
You don't need to pass it futher!
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
// put your save logic here
// save to file, send to email, etc.
// Also you can get information about throwed exception
// for example : ex.getMessage();
}
});
You need put Thread.setDefaultUncaughtExceptionHandler(...) to your Application class for the best case.
The second question is how does Fabric (Crashlytics) library work? Mind that I also don't want to spoil workflow of Fabric if it's also present in the application.
Fabric uses also UncaughtExceptionHandler
to catch all errors in your app.
Just filter logcat by Answers
tag. Or by System.exit
But how to pass it futher?
Before calling setDefaultUncaughtExceptionHandler()
, call getDefaultUncaughtExceptionHandler()
. Hold onto the old uncaught exception handler in your new one. When you are called with uncaughtException()
, do your own work and also call uncaughtException()
on the old handler.
How to crash application?
I usually divide some number by zero.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With