If you do not handle a runtime exception in your program, the default behaviour will be to terminate the program and dump the call stacktrace on the console.
Java provides an elegant mechanism of handling Runtime Exceptions that you might have not handled in your program.
UncaughtExceptionHandler can be defined at three levels. From highest to lowest they are:
Java provides an elegant mechanism of handling Runtime Exceptions that you might have not handled in your program.
UncaughtExceptionHandler can be defined at three levels. From highest to lowest they are:
- Thread.setDefaultUncaughtExceptionHandler
- ThreadGroup.uncaughtException
- Thread.setUncaughtExceptionHandler
package com.example.common;
import android.app.Activity;
public class TopExceptionHandler implements Thread.UncaughtExceptionHandler{
private Activity objApp;
public TopExceptionHandler(Activity app) {
objApp = app;
Thread.getDefaultUncaughtExceptionHandler();
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
// TODO Auto-generated method stub
try{
StackTraceElement[] arr = ex.getStackTrace();
String report = ex.toString();
String strStack = "";
strStack += "Stack trace: ";
for (int i=0; i<arr.length; i++){
strStack += " "+arr[i].toString()+"\t";
}
// If the exception was thrown in a background thread inside
// AsyncTask, then the actual exception can be found with getCause
String strCause = "";
strCause += "Cause: ";
Throwable cause = ex.getCause();
}
catch(Exception ex1){
System.err.println(ex1);
}
}
}
public class MyActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
new TopExceptionHandler(this);
}
}
Run the app and check Logcat for all runtime exceptions.
No comments :
Post a Comment