I want to stop my app from being crashed due to uncaught exception. I want exception to be store in log and prevent application from getting crashed. How do i achieve this ?. Thanks in advance.

- 331
- 1
- 7
- 21

- 57
- 2
- 6
-
2Without code and logcat how can we answer ? – IntelliJ Amiya Oct 03 '17 at 07:27
-
2We all want our application not to crash ;). Sometimes its possible to prevent it and others not. But without code... its impossible – Ivan Oct 03 '17 at 07:31
-
1@Ivan Thank You! for your comment. But you did not get what i`m trying to say. – Asad Shafique Oct 03 '17 at 08:28
3 Answers
For this your just need two classes Just copy paste them . This class is called when any exception occur within your application.
public class CrashHandler implements
java.lang.Thread.UncaughtExceptionHandler {
private final Context myContext;
private final String LINE_SEPARATOR = "\n";
public CrashHandler(Context context) {
myContext = context;
}
public void uncaughtException(Thread thread, Throwable exception) {
StringWriter stackTrace = new StringWriter();
exception.printStackTrace(new PrintWriter(stackTrace));
StringBuilder errorReport = new StringBuilder();
errorReport.append("************ CAUSE OF ERROR ************\n\n");
errorReport.append(stackTrace.toString());
errorReport.append("\n************ DEVICE INFORMATION ***********\n");
errorReport.append("Brand: ");
errorReport.append(Build.BRAND);
errorReport.append(LINE_SEPARATOR);
errorReport.append("Device: ");
errorReport.append(Build.DEVICE);
errorReport.append(LINE_SEPARATOR);
errorReport.append("Model: ");
errorReport.append(Build.MODEL);
errorReport.append(LINE_SEPARATOR);
errorReport.append("Id: ");
errorReport.append(Build.ID);
errorReport.append(LINE_SEPARATOR);
errorReport.append("Product: ");
errorReport.append(Build.PRODUCT);
errorReport.append(LINE_SEPARATOR);
errorReport.append("\n************ FIRMWARE ************\n");
errorReport.append("SDK: ");
errorReport.append(Build.VERSION.SDK);
errorReport.append(LINE_SEPARATOR);
errorReport.append("Release: ");
errorReport.append(Build.VERSION.RELEASE);
errorReport.append(LINE_SEPARATOR);
errorReport.append("Incremental: ");
errorReport.append(Build.VERSION.INCREMENTAL);
errorReport.append(LINE_SEPARATOR);
Intent intent = new Intent(myContext, ExceptionDisplay.class);
intent.putExtra("error", errorReport.toString());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
myContext.startActivity(intent);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(10);
}
}
Now make an Activity that displayed the error :-
public class ExceptionDisplay extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.exception_display_layout);
TextView exception_text = (TextView) findViewById(R.id.exception_text);
Button btnBack = (Button) findViewById(R.id.btnBack);
exception_text.setText(getIntent().getExtras().getString("error"));
btnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
intentData();
}
});
}
@Override
public void onBackPressed() {
intentData();
}
public void intentData() {
Log.d("CDA", "onBackPressed Called");
Intent setIntent = new Intent(ExceptionDisplay.this, AppDataSourceSelection.class);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
}
}
Now you can call this class by the class that extends application Class:
public class ErrorHandler extends Application {
@Override
public void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(new CrashHandler(getApplicationContext()));
}}

- 1,164
- 3
- 14
- 39
-
-
-
1Can we report crashes to firebase console in case of crashlytics applied ? – garry Sep 26 '18 at 06:23
-
@garry you can send all the report as a string to firebase database. – Abhishek Bhardwaj Sep 27 '18 at 07:08
-
2@Abhishek Bhardwaj Could you please show us the class `AppDataSourceSelection.class` too? Thanks in advance – BWappsAndmore Jun 26 '20 at 12:13
-
-
You can handle the uncaught exceptions yourself by this. Use below code into your application class.
public class MyApplication extends Application {
private UncaughtExceptionHandler defaultUEH;
private Thread.UncaughtExceptionHandler _unCaughtExceptionHandler =
new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
// here I do logging of exception to a db
Log.d("MyApp", "Uncaught exception.");
// Do what you want.
// re-throw exception to O.S. if that is serious and need to be handled by o.s. Uncomment the next line that time.
//defaultUEH.uncaughtException(thread, ex);
}
};
public MyApplication() {
defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
// setup Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
}
}

- 451
- 3
- 14
You can use try catch block to catch the exception by this way you can prevent your application from being crashing. In catch block get the expected exception and log that for your help. but remember not every exception can be caught Because some exceptions don't derive from Exception - e.g. Throwable and Error.
Basically the type hierarchy is:
Object
|
Throwable
/ \
Exception Error
Only Throwables and derived classes can be thrown, so if you catch Throwable, that really will catch everything.
Any exception deriving from Exception (or Exception itself) other than those derived from RuntimeException count as checked exceptions - they're the ones that you have to declare you'll throw, or catch if you call something that throws them.
All told, the Java exception hierarchy is a bit of a mess...

- 4,540
- 6
- 35
- 58
-
ah so I've been looking for some way to get my app to log something before it crashes.... I tried checking logcat but no uncaught exceptions in there as well... took me two days but I'm glad i found this answer and took no more than a minute to figure out where the issue lied.... Thanks man, you made my day :) – dev404 Oct 04 '21 at 13:27
-