Is there a code example, or a tutorial on how to use the Thread.setDefaultUncaughtExceptionHandler
method? Basically I'm trying to display a custom alert dialog, whenever an exception is thrown, in my application. Is it possible to do this? I know it's a little bit tricky to display something on the screen, if the exception is thrown in the UI thread but I don't know any work around for this.
How Exceptions Work in JVM and Android. In Java, all exception and error types are subclasses of Throwable. The Throwable class changes the execution flow of JVM apps by throwing exceptions and deciding how to recover from an error. Adding an exception to a code changes its execution flow.
In the Design tab part of the Ribbon, select New > Global Handler. The New Global Handler window opens. Type in a Name for the handler and save it in the project path. Click Create, a Global Exception Handler is added to the automation project.
First, we need to set up the capability of throwing exceptions on core banking service errors. Open core banking service and follow the steps. Create a common exception class where we going to extend RuntimeException. After that, we can create custom runtime exceptions to use with this API.
Basic Example for someone who comes to this page with a solution :)
public class ChildActivity extends BaseActivity { @SuppressWarnings("unused") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int a=1/0; } }
Class for handling error:
public class BaseActivity extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread paramThread, Throwable paramThrowable) { Log.e("Alert","Lets See if it Works !!!"); } }); } }
Here's a variant of the answer by Mohit Sharma with the following improvements:
Code:
public class BaseActivity extends Activity { @Override public void onCreate() { super.onCreate(); final Thread.UncaughtExceptionHandler oldHandler = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException( Thread paramThread, Throwable paramThrowable ) { //Do your own error handling here if (oldHandler != null) oldHandler.uncaughtException( paramThread, paramThrowable ); //Delegates to Android's error handling else System.exit(2); //Prevents the service/app from freezing } }); } }
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