样品code来处理异常样品、异常、code

2023-09-04 11:49:11 作者:Trust 信任

我是新来的Andr​​oid移动应用程序的开发。 我想知道,我怎么能处理像的HttpConnection 异常相关的异常或者其他异常?我是否需要显示一个 AlertDialog 用户?

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 exceptions? Do I need to display an AlertDialog to the user?

请提供关于如何处理一个样本code或项目源$ C ​​$ C 的HttpConnection 或相似类型的例外。

Kindly provide a sample code or project source code on how can I handle HttpConnection or similar type of Exceptions.

推荐答案

您如何处理异常取决于异常。如果异常的东西,你不能恢复,用户需要了解的,那么你可以捕获该异常,并显示在一个AlertDialog:

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());
}
 
精彩推荐
图片推荐