亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

可選的 throw 需要 NPE 的 throws 聲明

可選的 throw 需要 NPE 的 throws 聲明

慕娘9325324 2023-03-31 09:24:40
當為可為 null 的可選項拋出異常時,我遇到編譯錯誤,要求我捕獲異?;驅惓B暶鳛橐褣伋?,但 NPE 是不需要捕獲的運行時異常。所以基本上 orElseThrow 行為與拋出 java 8 之前的異常不同。這是一個特性還是一個錯誤?有什么想法嗎?這不編譯:protected String sendTemplate() {    String template = getTemplate();    return Optional.ofNullable(template).orElseThrow(() -> {        throw new NullPointerException("message");    });}這確實:protected String sendTemplate() {    String template = getTemplate();    if (template == null){        throw new NullPointerException("message");    }    else return template;}
查看完整描述

2 回答

?
ibeautiful

TA貢獻1993條經驗 獲得超6個贊

傳遞Supplier給orElseThrow應該返回構造的異常,該異常與該方法的通用簽名相關,該方法聲明拋出供應商返回的內容。由于您的供應商沒有返回值,JDK 8javac推斷Throwable并要求調用者orElseThrow處理它。較新的編譯器可以在這種情況下方便地進行推斷RuntimeException,并且不會產生錯誤。


不過,正確的用法是


protected String sendTemplate1() {

? ? String template = getTemplate();

? ? return Optional.ofNullable(template)

? ? ? ? .orElseThrow(() -> new NullPointerException("message"));

}

但這是對Optionalanyway 的過度使用。你應該簡單地使用


protected String sendTemplate() {

? ? return Objects.requireNonNull(getTemplate(), "message");

}

requireNonNull(T, String)requireNonNull(T, Supplier<String>)。



查看完整回答
反對 回復 2023-03-31
?
白衣非少年

TA貢獻1155條經驗 獲得超0個贊

改變這個


protected String sendTemplate() {

? ? String template = getTemplate();

? ? return Optional.ofNullable(template).orElseThrow(() -> {

? ? ? ? throw new NullPointerException("message");

? ? });

}

這樣:


protected String sendTemplate() {

? ? String template = getTemplate();

? ? return Optional.ofNullable(template).orElseThrow(() -> {

? ? ? ? return new NullPointerException("message"); // <--- RETURN here

? ? });

}

方法orElseThrow()需要一個供應商(即創建異常的東西)。你不能拋出異常,只是創建它。



查看完整回答
反對 回復 2023-03-31
  • 2 回答
  • 0 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號