【问题标题】:Debugging return statement within catch block在 catch 块中调试 return 语句
【发布时间】:2014-04-21 07:39:25
【问题描述】:

我正在开发一个使用以下 sn-p 的 android 应用程序:

private Boolean myMethod(boolean isOnline) {
    try {
        if (isOnline) {
            ...
            return true;    
        } 
        else {
            ...
            return true;
        }
    } 
    catch (SocketTimeoutException e) {
        this.e = e;
        return false;
    } catch (IOException e) {
        this.e = e;
        return false;
    } catch (XmlPullParserException e) {
        this.e = e;
        return false;
    } catch (Exception e) { 
        this.e = e;
        return false;
    }
}

在我调试代码时。最后一个catch块return false;中的return语句在不执行this.e = e;的情况下执行,this.enull。如果我删除最后一个 catch 块

catch (Exception e) { 
    this.e = e;
    return false;
}

然后执行后面的catch块中的return语句

catch (XmlPullParserException e) {
    this.e = e;
    return false;
} 

我犯了什么错误?

【问题讨论】:

  • 执行这段代码时调用了哪个异常
  • 捕获Exception 通常是个坏主意,因为您可能会捕获一些与您不对应的Exception,因此您应该始终只捕获您知道try 的特定异常块可以抛出。这可能就是这里发生的情况,您输入的是Exception,因为它比XmlPullParserException 更通用。
  • 你想达到什么目的??
  • 你的意思是说当你捕获异常时,this.e 仍然为空??
  • @Amith GC。没错,你是对的。我需要做什么?

标签: java exception


【解决方案1】:

你的错误是添加了这个块:

catch (Exception e) { 
    this.e = e;
    return false;
}

它将捕获所有内容,导致您的 XmlPullParserException 不被称为 IMO。

【讨论】:

  • 真的吗?如果代码抛出 XmlPullParserException,实现的代码应该调用 XmlPullParserException,因为最后添加了异常。
  • 我尝试的一个小代码测试抛出 NullPointerException 并捕获 NullPointerExceptionException 并不真正同意你的答案。
  • 大家好,感谢您的反馈。我想我错了。
  • 但异常为空:-(
  • @RakeshL,这是一个非常奇怪的案例。除非我们看到所有相关代码,否则我们只是猜测。顺便问一下,你想要 this.e 做什么?
猜你喜欢
  • 2014-10-10
  • 2014-06-05
  • 2013-10-02
  • 2020-06-17
  • 2014-04-19
  • 2011-08-07
  • 2016-11-25
  • 2011-12-21
相关资源
最近更新 更多