1

How can I prevent my Android application from crashing if any exception happens in the activity code or service code in Java?

Here is the code example of an unhanded Exception from an Activity or Service:

public class MainActivity extends AppCompatActivity {   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        Integer.parseInt("error");
}

When this code is run, it crashes and produces the "Unfortunately, App has stopped" message.

swiftBoy
  • 35,607
  • 26
  • 136
  • 135
  • The exceptions are to help you to figure out what is wrong in your code. Don't try to make them silence, try to read and understand what's wrong with your code. – lev09 Aug 26 '16 at 16:52
  • The line `Integer.parseInt("error");` is unacceptable. The `Integer.parseInt()` method is used to parse integers (numbers) from string. like this `Integer.parseInt("5")` – lev09 Aug 26 '16 at 16:58
  • An exception occurs because there is some issues. For application to work even after the exception, the wrong thing needs to be repaired. How can you expect to repair the code without handling the exception? – Prerak Sola Aug 26 '16 at 17:01
  • Possible duplicate of [Can I catch multiple Java exceptions in the same catch clause?](http://stackoverflow.com/questions/3495926/can-i-catch-multiple-java-exceptions-in-the-same-catch-clause) – Laurel Aug 26 '16 at 21:29
  • Thank you for your answers but just i need to see unknown exception without crashing like https://github.com/idolon-github/android-crash-catcher – Mohammad Khir Alsaid Aug 28 '16 at 07:28

1 Answers1

-2

You can handle all the UncaughtExceptions in your Application class. Here's an implementation: https://github.com/idolon-github/android-crash-catcher

Monu Surana
  • 694
  • 1
  • 6
  • 20