Android: handle uncaught exceptions

To avoid the ‘unfortunately app has stopped‘ dialog box, you can handle all uncaught exceptions in your app by setting custom handler.

Uncaught exception Handler

Paste this code in the beginning of your app. This will setup the handler. Do it only once, for example in onCreate of your fisrt activity that is displayed to the user

Thread.setDefaultUncaughtExceptionHandler(
	new UncaughtExceptionHandler() {

		@Override
		public void uncaughtException(Thread thread, Throwable ex) {
			Log.e("Error", "Unhandled exception: " + ex.getMessage());
			Toast.makeText(getApplicationContext(), R.string.app_fatalError, Toast.LENGTH_LONG).show();
			System.exit(1);
		}
	});

Did I help you?
I manage this blog and share my knowledge for free, sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!

4 thoughts on “Android: handle uncaught exceptions

Give Your feedback: