Sample code to handle Exceptions

后端 未结 3 1788
野趣味
野趣味 2021-02-03 12:40

I am new to Android mobile application development. I would like to know, how can I handle exceptions like HttpConnection related exceptions or any other exception

3条回答
  •  说谎
    说谎 (楼主)
    2021-02-03 13:19

    How you handle exception depends on the exception. If the exception is something that you cannot recover from, and the user needs to know about then you could catch the exception and show it in an AlertDialog:

    try {
      // do something
    } catch (SomeImportantException e) {
      AlertDialog.Builder builder = new AlertDialog.Builder(this);
      builder.setMessage("User friendly text explaining what went wrong.");
      AlertDialog alert = builder.create();
      alert.show();
    }
    

    For more info on the dialog, see creating dialogs.

    Alternatively, if the exception is something that you can deal with, you can just log information about the exception and move on.

    try {
      // do something
    } catch (SomeLessImportantException e) {
      Log.d(tag, "Failed to do something: " + e.getMessage());
    }
    

提交回复
热议问题