Java:如何使用带返回的try / catch块

时间:2018-03-27 19:29:04

标签: java list exception

如果列表为空并且我想要getLast(),则以下代码会引发异常。此外,我想用throw/catch - 块修改它,以便异常消息将出现在控制台上。

double foo(double[] numbers, double n) {
    LinkedList<Double> list = new LinkedList<Double>();
    for (double x : numbers) {
        if (x > 0 && x <= n && x % 2 != 0) {
            list.add(x);
        }
    }

    Collections.sort(list);
    return list.getLast();
}

我的想法是:

double foo(double[] numbers, double n) {
    LinkedList<Double> list = new LinkedList<Double>();
    for (double x : numbers) {
        if (x > 0 && x <= n && x % 2 != 0) {
            list.add(x);
        }
    }

    Collections.sort(list);
    try{
        return list.getLast();
    } catch (Exception e){
        System.out.println("caught: " + e);
    }
    return list.getLast();
}

这是对的吗?异常被抓住了吗? throw/catch - 块之后的代码怎么样?它会执行吗?如果是,return list.getLast();会再次抛出异常吗?

3 个答案:

答案 0 :(得分:0)

  • 这是对的吗? 如果您希望在打印后抛出异常,则可能是功能正确的,但调用getLast()两次并不是“正确”的方法。
  • 异常被抓获了吗? 是的,确实如此。
  • throw / catch-block之后的代码怎么样?要执行吗? 是的,它会执行。由于异常被捕获而没有被重新抛出,因此执行继续照常进行。
  • 如果是,请返回list.getLast();是再次被抛出的例外吗? 是的,将再次抛出异常。

我认为你在寻找的是:

try {
    return list.getLast();
} catch (Exception e){
  System.out.println("caught: " + e); // consider e.printStackTrace()
  throw new RuntimeException("Failed to get last", e);
}
}

答案 1 :(得分:0)

如果list.getLast()抛出异常,它将被捕获并打印消息。然后你将完成完全相同的事情并抛出完全相同的异常。

如果您依赖于列表为空时抛出的异常,请考虑重新抛出异常:

try {
  return list.getLast();
} catch (Exception e) {
  System.err.println("Caught: " + e);
  throw e; // re-throw
}
// no "return" outside since we'll have thrown our previously caught error.

答案 2 :(得分:0)

为什么要使用try / catch。如果您要做的只是确定列表是否为空,那么检查list.size() != 0是什么?如果为true,则返回list.getLast()Double.Nan,如果为false,则返回控制台的消息。

相关问题