When writing an APK program, it usually causes program crash exceptions. In general, these exceptions cannot be caught. Use thread. uncaughtexceptionhandlerThese exceptions can be captured. It can be seen from the name that uncaughtexceptionhandlerIt is for a thread. At the same time, thread provides three related methods:
1. void setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) //
Set a handler for a thread
2. thread. uncaughtexceptionhandlerGetuncaughtexceptionhandLer () // Obtain the handler of the thread
3. Static void setdefaultuncaughtexceptIonhandler (thread. uncaughtexceptionhandlerEh)
// Set a default handler for a thread and exit when the program cannot be captured and other handler is called!
Therefore, you only need to use the set method to set a handler for a thread to capture and modify exceptions when the program exits unexpectedly,Demo1:
Thread thread = new thread(new Runnable(){
public void run() {
//Do something can throw runtime exception.
}
});
thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler(){
@Override
public void uncaughtException(Thread thread, Throwable ex) {
//TODO
System.out.println(ex.getLocalizedMessage());
});
An exception will be caught when the thread is running, and you can handle the caught exception.
However, because a large number of threads are used in Android programming, what if they are processed in a unified manner? Because there is only one main thread, we can process it in the main thread.
We can add the following code in the oncreate method when the main activity is started.
Thread. setdefaultuncaughtexceptIonhandler (New thread. uncaughtexceptionhandler(){
Public void uncaughtexception (thread, throwable ex ){
// Todo is called when an exception cannot be caught in the program. You can release the resource, disconnect the connection, and perform friendly prompts here!
System.out.println(ex.getLocalizedMessage());
finish();
}
});
In this way, most runtime exceptions can be captured.