用于处理异常的示例代码 [英] Sample code to handle Exceptions

查看:265
本文介绍了用于处理异常的示例代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android移动应用开发的新手。
我想知道,我如何处理像 HttpConnection 相关异常或任何其他异常的异常?我需要向用户显示一个 AlertDialog



请提供示例代码或项目源代码我可以处理 HttpConnection 或类似的例外类型。

解决方案

处理异常取决于异常。如果异常是您无法恢复的,用户需要知道的话,您可以捕获异常并将其显示在AlertDialog中:

  try {
// do something
} catch(SomeImportantException e){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(用户友好的文本解释出了什么问题);
AlertDialog alert = builder.create();
alert.show();
}

有关对话框的更多信息,请参阅创建对话框



或者,如果例外是你可以处理的事情,你可以只记录关于异常的信息并继续前进。

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


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?

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

解决方案

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());
}

这篇关于用于处理异常的示例代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆