簡體   English   中英

Java:如何在try / catch塊中使用return

[英]Java: how to use try/catch block with return

如果列表為空並且我想要getLast()則以下代碼將引發異常。 另外,我想使用throw/catch -blocks對其進行修改,以使異常消息將出現在控制台上。

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 -block之后的代碼呢? 它要執行嗎? 如果是,則將由return list.getLast();再次引發異常return list.getLast();

  • 這是正確的嗎? 如果要在打印后引發異常,則可能在功能上是正確的,但是兩次調用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);
}
}

如果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.

為什么要完全使用try / catch。 如果您只想確定列表是否為空,那么檢查list.size() != 0怎么辦? 然后,如果為true或Double.Nan ,則返回list.getLast()如果為false,則返回一條消息到控制台。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM