3 回答

TA貢獻1876條經(jīng)驗 獲得超6個贊
解釋
讓我快速引用重要部分:
throw
在塊內(nèi)使用語句finally
會破壞 try-catch-finally 的邏輯進程。在 Java 中,finally 塊始終在相應(yīng)的 try-catch 塊之后執(zhí)行,并且通常用于釋放分配的資源,例如文件句柄或數(shù)據(jù)庫游標(biāo)。在 finally 塊中拋出異常可以繞過關(guān)鍵的清理代碼,因為正常的程序執(zhí)行將被中斷。
因此,您可以通過這樣做輕松繞過清理代碼,從而導(dǎo)致資源泄漏。
雖然在代碼中不直接可見,但實際上有一個隱藏?finally
塊,因為您使用的是try-with-resources,它會自動關(guān)閉 finally 塊中的資源。
例子
這是官方文檔中的示例:
public void processTransaction(Connection conn) throws FileNotFoundException {
? ? FileInputStream fis = null;
? ? Statement stmt = null;
? ? try {
? ? ? ? stmt = conn.createStatement();
? ? ? ? fis = new FileInputStream("badFile.txt");
? ? ? ? ...
? ? } catch (FileNotFoundException fe) {
? ? ? ? log("File not found.");
? ? } catch (SQLException se) {
? ? ? ? // handle error
? ? } finally {
? ? ? ? if (fis == null) {
? ? ? ? ? ? // This bypasses cleanup code
? ? ? ? ? ? throw new FileNotFoundException();
? ? ? ? }
? ? ? ? if (stmt != null) {
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? // Not executed if the exception is thrown
? ? ? ? ? ? ? ? stmt.close();
? ? ? ? ? ? }
? ? ? ? ? ? catch (SQLException e) {
? ? ? ? ? ? ? ? log(e);
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
拋出時繞過stmt.close()
對的調(diào)用。FileNotFoundException
筆記
為什么要檢查是否null
使用 aNullPointerException
而不是基本的if-else?很少有正當(dāng)理由去抓捕NullPointerException
。做就是了:
try (InputStream resource = ErrorResource.classLoader.getResourceAsStream(fileName)) {
? ? if (resource == null) {
? ? ? ? // TODO Throw your exception here
? ? }
? ? return new String(resource.readAllBytes(), StandardCharsets.UTF_8);
}
通過告知無法找到資源的確切原因,它也可能有助于改進錯誤消息。

TA貢獻1872條經(jīng)驗 獲得超4個贊
考慮以下代碼,它大致基于您的代碼:
String throwing(InputStream inputStream) throws IOException {
try (InputStream resource = inputStream) {
return "good";
} catch (NullPointerException n) {
return "bad";
}
}
你看,這里沒有拋出異常。盡管如此,你還是無法移除這個throws IOException部分——那是怎么回事?好吧,InputStream#close()可以拋出它,它將位于finallytry-with-resources 語句創(chuàng)建的隱式塊中。我想您對此無能為力,它看起來像是 Fortify 誤報。

TA貢獻1834條經(jīng)驗 獲得超8個贊
除了工具中的誤導(dǎo)性消息之外,您的代碼中實際上存在糟糕的錯誤處理,原因有多種:
捕捉 NPE 是非常糟糕的做法。要么它是一個錯誤(某些東西是 null 并且不應(yīng)該),要么你的代碼缺少檢查
if (whatever == null)
和相應(yīng)的代碼來處理這種預(yù)期情況假設(shè)這個 NPE 具有您在新 Exception 中表達的確切含義,只是猜測
換句話說:在沒有更多信息的情況下,不清楚您的工具到底抱怨什么。但是:不需要工具來理解:這是糟糕的錯誤處理。
除此之外,此類工具通常會提供有關(guān)其警告的某種信息。意思是:該警告可能帶有一個“錯誤 ID”,您應(yīng)該能夠在您的工具文檔中查找該“錯誤 ID”以獲得進一步的解釋。
添加回答
舉報