【问题标题】:Use try/catch in manner of if else, but with exceptions as condition?以 if else 的方式使用 try/catch,但将异常作为条件?
【发布时间】:2016-03-05 21:43:33
【问题描述】:
  • 如果我在列表中搜索某个元素但没有找到, 我抛出一个 NotInListException
  • 否则我想将其添加到另一个列表中

我做到了

try {

    element = actualList.find("foo");
    anotherList.append(element);

}
catch (NotInListException e) {
}

这种用法好吗?或者我应该像这样重构它:

if ((element = actualList.find("foo")) != null) {
    anotherList.append(element);
}

【问题讨论】:

  • 我更喜欢if (!actualList.contains(element)) anotherList.append(element);
  • 谢谢,这看起来更“自然”。
  • 没有实现 List 我知道有 find() 方法,什么是 NotInListException?这段代码到底是什么?

标签: java exception try-catch


【解决方案1】:

如果您忽略异常处理程序给出的小运行时惩罚,这就是风格问题。

可以设计一个类似的堆栈类型

try{
while(true){
    try{
        stack.pop();
    catch(StackElement e){
        processElement(e);
    }
}
catch(EmptyStackException ese){
    // probably not much to do here. 
}

出于可读性和常识的原因,共识是,通常的if 条件使事情更容易理解。异常机制应该用于异常情况,而不是用于常规流控制。

在您的特定查找示例中,您有两个案例,没有一个是不寻常的。所以例外可能是不必要的。

1 - 没有找到该元素。

2 - 找到元素。

情况 2 需要额外注意,因为您的 find 版本也希望返回实际元素。

1 || 2 是布尔情况。所以这不应该是一个元素。案例 2 的 find() 应该是一个元素。

我一直不喜欢非值返回 null。它会产生丑陋的代码。回想一下

void f(BufferedReader br){
    String line;
    while( (line = br.readLine()) != null)

更好的是将布尔值与元素分开。

if( list.has(foo) ){
    E element = list.get(foo);
}

【讨论】:

    【解决方案2】:

    您的第二个示例更加简洁易读。您没有提供任何详细信息,但我想在您的搜索中未找到值不应被视为特殊情况。

    使用 Java 8,您甚至可以考虑返回 Optional 并添加如下结果:

    actualList
        .find("foo")
        .ifPresent(v -> anotherList.add(v));
    

    【讨论】:

      【解决方案3】:

      我相信您的代码应该遵循逻辑原则。如果问题是抛出或不抛出 NotInListException,那么要回答的先决问题是:不在列表中的元素是例外情况吗?我们真的期望那个元素在列表中吗?如果答案是肯定的,那么元素不在列表中的情况是异常的,因此,抛出异常是有意义的。否则应该是 if-else 逻辑。

      【讨论】:

        【解决方案4】:

        我会推荐这样写:

        List<String> elements; //get the list
        try{
            if(elements.contains("foo")){
                anotherList.add("foo");
            }else{
                throw new NotInListException("Element not present");
            }
        }catch(NotInListException ex){
            //do something
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多