0

Is there a way to catch, in one place, all "uncaught" exceptions and let the app continue?

I see I can use setUncaughtExceptionHandler to do some logging and whatever, but the app will still terminate. I want something where I can log an exception, tell the user his action failed, and let him keep going (try something else).

Thanks.

Peri Hartman
  • 19,314
  • 18
  • 55
  • 101

2 Answers2

2

No. I'm not sure why you'd want it. Catch Exceptions from methods that are known to throw them, and test your code to avoid Exceptions such as NullPointerException. That's the way to write good code.

Joe Malin
  • 8,621
  • 1
  • 23
  • 18
  • Pretty much any method can throw an exception. Many (say, due to coding bugs) can't really be handled, so I don't see much advantage at cathing them at a deeper level. Might as well catch them all at the top level. Sure, other kinds of errors, like an import parsing error, are best caught near the source. I do that. Now, I'm looking for a solution for the rest. – Peri Hartman Dec 20 '12 at 23:09
  • `Many (say, due to coding bugs) can't really be handled`... interesting. I can handle any error and I believe: A mobile app is one of the most interactive programs out there, so developers better handle exceptions decently. – Sherif elKhatib Dec 20 '12 at 23:18
  • Sure, you can handle it. But, if you fault because of a null pointer exception for example, all you can do is tell the user something went wrong, log something, and go on. That's all I want to do, except I'd like to do it at a higher level rather than pepper the code with try-catch. – Peri Hartman Dec 21 '12 at 00:11
0

Sorry to revisit such an old thread but since there's no proper answer to it I felt obliged to provide a solution.

Add this to the activity that opens every time the app is used (MainActivity for example) -

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
                Log.e("Exception"+Thread.currentThread().getStackTrace()[2],paramThrowable.getLocalizedMessage());
            } 
        });

What it does is that it sets a default handler for uncaught exceptions and doesn't quit the app when one pops up. However, with great power comes great responsibility. I don't recommend you use this as a way to escape the responsibility of catching exceptions in your code (by using a try-catch for example). Test your code to make it as bug-free as possible before launch.

Advait Saravade
  • 3,029
  • 29
  • 34