I'm using a crash report library in my Android project. Once activated, it reacts to every uncatched exception and creates a report just before the app shutdown.
So far so good, but I want to add more "control" to this thing and create reports for non-Exceptions too. My idea is to define a "fake" Exception this way:
public final class NonFatalError extends RuntimeException {
private static final long serialVersionUID = -6259026017799110412L;
public NonFatalError(String msg) {
super(msg);
}
}
So, when I want to send a non-fatal error message and create a report, I'll do this:
throw new NonFatalError("Warning! A strange thing happened. I report this to the server but I let you continue the job...");
If called from the main thread, this obviously makes the app crash. So, I tried to throw it on a background thread!
new Thread(new Runnable() {
@Override
public void run() {
throw new NotFatalError("Warning! A strange thing happened. I report this to the server but I let you continue the job...");
}
}).start();
A great idea? No. The app crashes anyway (but the fake crash report is sent as expected). Is there another way to achieve what I want?
Your exception never gets caught, so that's why your application is crashing.
You can do this do catch the exception from your main thread:
Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread th, Throwable ex) {
System.out.println("Uncaught exception: " + ex);
}
};
Thread t = new Thread(new Runnable() {
@Override
public void run() {
throw new NotFatalError("Warning! A strange thing happened. I report this to the server but I let you continue the job...");
}
});
t.setUncaughtExceptionHandler(h);
t.start();
But you can also run the code from your main thread and catch it there.. Like:
try
{
throw new NonFatalError("Warning! blablabla...");
}
catch(NonFatalError e)
{
System.out.println(e.getMessage());
}
Because your exception is extended from the RuntimeException
class the default behaviour is to exit the application if the exception is not catched anywhere. So that's why you should catch it before the Java Runtime decides to quit the app.
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