TheUnexpected
TheUnexpected

Reputation: 3167

Throw an Exception without crashing the app

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?

Upvotes: 6

Views: 11536

Answers (2)

Wessel van der Linden
Wessel van der Linden

Reputation: 2622

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.

Upvotes: 5

Sandro Machado
Sandro Machado

Reputation: 10205

You are using exception to create logs. You shouldnt do that. If you are using a library like crashlytics (https://try.crashlytics.com/) you can send log reports like in this link: http://support.crashlytics.com/knowledgebase/articles/120066-how-do-i-use-logging

The library you are using should have a similar method.

If you want to continue to use Exceptions, you need to catch them to not crash the application.

Upvotes: 0

Related Questions