java 处理异常的示例代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3805855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:27:19  来源:igfitidea点击:

Sample code to handle Exceptions

javaandroidexception

提问by chiranjib

I am new to Android mobile application development. I would like to know, how can I handle exceptions like HttpConnectionrelated exceptions or any other exceptions? Do I need to display an AlertDialogto the user?

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

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

请提供有关如何处理HttpConnection或类似类型异常的示例代码或项目源代码。

回答by paiego

There are 2 different kinds of exceptions in Java: Checked and Unchecked. There is a big debate over which one is better to use, both arguments are good.

Java 中有两种不同类型的异常:Checked 和 Unchecked。关于使用哪个更好,存在很大的争论,这两种论点都很好。

Basically a Checked exception is derived from java.lang.Exceptionand it requires that if you don't specify your method as "throws MyCheckedException" then you must catch and handle the exception within your method.

基本上,Checked 异常派生自java.lang.Exception它,它要求如果您没有将您的方法指定为“throws MyCheckedException”,那么您必须在您的方法中捕获并处理该异常。

// throw the exception

void foo() throws MyCheckedException
{
    throw new MyCheckedException();
}

// or handle the exception

void foo()
{
    try {
       throw new MyCheckedException();
    } catch (MyRuntimeException e) {
        e.printStackTrace();
    }
}

An Unchecked exception, derived from java.lang.RuntimeException, requires neither that you specify "throws" in your method definition nor that you handle it.

派生自 的 Unchecked 异常java.lang.RuntimeException既不需要您在方法定义中指定“throws”,也不需要您处理它。

void foo()
{
    throw new MyUncheckedException();
}

The advantage of Checked is that the compiler will warn you when you haven't handled an exception.

Checked 的优点是当你没有处理异常时编译器会警告你。

The disadvantage is that you have to declare either a try/catch block or a throws for every Checked exception, and the upper level code can get pretty cumbersome, trying to handle all the different types of Exceptions.

缺点是您必须为每个 Checked 异常声明 try/catch 块或 throws,并且上层代码会变得非常繁琐,试图处理所有不同类型的异常。

For this reason, if you're careful you might prefer using Unchecked Exceptions.

出于这个原因,如果您小心的话,您可能更喜欢使用 Unchecked Exceptions。

BTW, you can only choose your exception type when you define your own.

顺便说一句,您只能在定义自己的异常类型时选择异常类型。

When encountering Exceptions from Java or a 3rd party library, you have to decide how to handle it. e.g. If a 3rd party method throws CheckedException1, then you have to either handle it, or declare the calling method as "throws CheckedException1". If you want to avoid using Checked Exceptions then you can wrap it in an Unchecked Exception and throw that.

当遇到来自 Java 或第三方库的异常时,您必须决定如何处理它。例如,如果第 3 方方法抛出 CheckedException1,那么您必须处理它,或者将调用方法声明为“throws CheckedException1”。如果你想避免使用检查异常,那么你可以将它包装在一个未检查异常中并抛出它。

void foo() // no throws declaration
{
    try {
        thirdPartyObj.thirdPartyMethod(); // this throws CheckedException1
    }
    catch (CheckedException1 e) {
        throw new MyUncheckedException(e); // this will wrap the checked in an unchecked.
    }
}

Note that you can throw the Unchecked exception without the "throws" declaration. To access the original CheckedException1 from higher up, you can use the .getCause() method of your Unchecked exception.

请注意,您可以在没有“throws”声明的情况下抛出 Unchecked 异常。要从更高层访问原始 CheckedException1,您可以使用 Unchecked 异常的 .getCause() 方法。

void caller()
{
    try {
        foo();
    } catch (MyUncheckedException e) {
        CheckedException1 ce1 = e.getCause();
        ce1.printStackTrace();
    }
}

... but because the exception from foo() is Unchecked, you don't haveto handle it or declare "throws".

...但由于从富(除外)未选中,你不具备办理或者申报“抛出”。

Regarding logging, there are different schools of thought on this.

关于伐木,对此有不同的思想流派。

  1. Log it when the exception occurs (low - level)
  2. Log it when it reaches the top (high - level)
  3. Log it when you have enough information to make an appropriate action and/or a log message. (mid - level)
  1. 异常发生时记录(低级)
  2. 当它到达顶部时记录它(高级)
  3. 当您有足够的信息来执行适当的操作和/或记录消息时,记录它。(中级)

A good policy I've found is to install an uncaught exception handler which will take care of all uncaught (obviously unchecked) exceptions. This way anything that is missed will be logged and potentially handled before crashing the system.

我发现的一个好策略是安装一个未捕获的异常处理程序,它将处理所有未捕获的(显然是未经检查的)异常。这样,任何遗漏的东西都将被记录下来,并可能在系统崩溃之前进行处理。

public class MyExceptionHandler implements UncaughtExceptionHandler 
{       
    @Override
    public void uncaughtException(Thread thread, Throwable ex)
    {
        ex.printStackTrace();
    }
}

// In your high-level code
Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler());

and all for Exceptions that can be handled gracefully, catch and handle them in a module where you know enough about the situation to possibly correct the problem and try again.

以及所有可以正常处理的异常,在一个模块中捕获并处理它们,在该模块中您对情况有足够的了解以可能纠正问题并重试。

回答by Cheryl Simon

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:

您如何处理异常取决于异常。如果异常是您无法从中恢复的,并且用户需要了解,那么您可以捕获异常并将其显示在 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());
}

回答by PanosJee

You could use the ACRA plugin that offers this functionality or BugSenseto gather error reports. Disclaimer: I am a founder at BugSense.

您可以使用提供此功能的 ACRA 插件或BugSense来收集错误报告。免责声明:我是 BugSense 的创始人。