自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

一篇文章徹底理解 Java 的 Suppressed exceptions 機(jī)制

開發(fā) 前端
在查看 JAVA 應(yīng)用拋出的異常堆棧以排查問題時,我們有時會看到所謂 suppressed exceptions,即被抑制的異常。理解 suppressed exceptions 的原理,對我們分析問題的底層真實原因大有裨益。所以本文分析總結(jié)下 Java 中的 suppressed exceptions。

1. 前言

在查看 JAVA 應(yīng)用拋出的異常堆棧以排查問題時,我們有時會看到所謂 suppressed exceptions,即被抑制的異常。理解 suppressed exceptions 的原理,對我們分析問題的底層真實原因大有裨益。所以本文分析總結(jié)下 Java 中的 suppressed exceptions。

2. suppressed exceptions 機(jī)制總結(jié)

  • 簡單來說,suppressed exceptions 是 JVM 中一個真實發(fā)生了的異常,但由于某些原因被 JVM 忽略/抑制了;
  • 一個常見的異常被忽略/抑制的場景是 try-catch-finally 代碼塊:由于無論 try 代碼塊是否正常執(zhí)行結(jié)束,finally 代碼塊都會執(zhí)行,所以如果 try 代碼塊和 finally 代碼塊都拋出異常時,為在打印的異常堆棧中完整還原異?,F(xiàn)場,代碼中可以做特殊處理(具體的處理方式見后文),以將兩個異常都打印,并標(biāo)記 try 中的異常為 suppressed;(用戶需要對異常代碼做處理);
  • 另一個常見的異常被忽略的場景是 try-with-resources 代碼塊:java7 引進(jìn)了 try-with-resources 代碼塊和 AutoCloseable 接口來管理資源,當(dāng) try-with-resources 底層的業(yè)務(wù)邏輯代碼執(zhí)行完畢時,無論其執(zhí)行是否正常結(jié)束,jvm 都會自動關(guān)閉 try 中指定的 AutoCloseable 資源,以避免資源泄露,如果業(yè)務(wù)邏輯代碼的處理和 AutoCloseable 資源的關(guān)閉都發(fā)生了異常,此時 jvm 會將兩個異常都打印,并標(biāo)記關(guān)閉 AutoCloseable 資源觸發(fā)的異常為try 中的異常為 suppressed;(用戶不用做特殊處理);
  • 所以,為有效利用 suppressed exceptions 機(jī)制妥善打印異常堆棧以輔助問題排查,從 Java 7 開始, 我們可以使用 Throwable 類的如下方法來處理 suppressed exceptions: 即 java.lang.Throwable#addSuppressed 和java.lang.Throwable#getSuppressed
  • A suppressed exception is an exception that is thrown but somehow ignored;
  • A common scenario for this is the try-catch-finally block: when the finally block throws an exception,any exception originally thrown in the try block is then suppressed;
  • Another common scenario is the try-with-resources block:Java 7 introduced the try-with-resources construct and the AutoCloseable interface for resource management,when exception occurs both in the business processing and resource closing,it’s the exception thrown in the close method that’s suppressed;
  • Starting with Java 7, we can now use two methods on the Throwable class to handle our suppressed exceptions: addSuppressed and getSuppressed.

3 suppressed exceptions 機(jī)制 細(xì)節(jié)- try-catch-finally 代碼塊

  • 當(dāng) finally 代碼塊沒有使用 java.lang.Throwable#addSuppressed 對異常進(jìn)行特殊處理時,如果 try 代碼塊和 finally 代碼塊都拋出異常,打印的異常堆棧的示例如下,可以看到,沒有打印try 中的異常,而僅僅打印了 finally 中的異常,此時用戶顯然無法輕易獲知異常的真實原因;
java.lang.NullPointerException
at com.keep.bdata.SuppressedExceptionsDemo.demoExceptionWithNoSuppress(SuppressedExceptionsDemo.java:21)
at com.keep.bdata.SuppressedExceptionsDemo.givenNonExistentFileName_whenAttemptFileOpen_thenNullPointerException(SuppressedExceptionsDemo.java:12)

圖片圖片

  • 當(dāng) finally 代碼塊使用 java.lang.Throwable#addSuppressed 對異常進(jìn)行了特殊處理時,如果 try 代碼塊和 finally 代碼塊都拋出異常,打印的異常堆棧的示例如下,可以看到,try 中的異常和 finally 中的異常都被打印了,且 try 中的異常被標(biāo)記為 suppressed exceptions, 如果用戶理解 suppressed exceptions 的機(jī)制,通過這些異常堆棧,顯然可以輕松獲知異常的真實原因;
java.lang.NullPointerException
	at com.keep.bdata.SuppressedExceptionsDemo.demoExceptionWithSuppressed(SuppressedExceptionsDemo.java:38)
	at com.keep.bdata.SuppressedExceptionsDemo.givenNonExistentFileName_whenAttemptFileOpen_thenNullPointerException_withSuppressed(SuppressedExceptionsDemo.java:27)
	Suppressed: java.io.FileNotFoundException: \non-existent-path\non-existent-file.txt (系統(tǒng)找不到指定的路徑。)
		at java.io.FileInputStream.open0(Native Method)
		at java.io.FileInputStream.open(FileInputStream.java:195)
		at java.io.FileInputStream.<init>(FileInputStream.java:138)
		at java.io.FileInputStream.<init>(FileInputStream.java:93)
		at com.keep.bdata.SuppressedExceptionsDemo.demoExceptionWithSuppressed(SuppressedExceptionsDemo.java:33)

圖片圖片

4 suppressed exceptions 機(jī)制 細(xì)節(jié) - try-with-resources 代碼塊

  • java7 引進(jìn)了 try-with-resources 代碼塊和 AutoCloseable 接口來管理資源,當(dāng) try-with-resources 底層的業(yè)務(wù)邏輯代碼執(zhí)行完畢時,無論其執(zhí)行是否正常結(jié)束,jvm 都會自動關(guān)閉 try 中指定的 AutoCloseable 資源,以避免資源泄露;
  • 如果業(yè)務(wù)邏輯代碼的處理和 AutoCloseable 資源的關(guān)閉都發(fā)生了異常,此時 jvm 會將兩個異常都打印,并標(biāo)記關(guān)閉 AutoCloseable 資源觸發(fā)的異常為try 中的異常為 suppressed,打印的異常堆棧的示例如下,如果用戶理解 suppressed exceptions 的機(jī)制,通過這些異常堆棧,顯然可以輕松獲知異常的真實原因;
  • 注意這是jvm自己實現(xiàn)的,用戶不需要對代碼做特殊處理;
java.lang.IllegalArgumentException: Thrown from processSomething()
	at com.keep.bdata.TryWithResourceDemo$ExceptionalResource.processSomething(TryWithResourceDemo.java:23)
	at com.keep.bdata.TryWithResourceDemo.demoExceptionalResource(TryWithResourceDemo.java:17)
	at com.keep.bdata.TryWithResourceDemo.givenNonExistentFileName_whenAttemptFileOpen_thenNullPointerException_suppressed(TryWithResourceDemo.java:12)
	Suppressed: java.lang.NullPointerException: Thrown from close()
		at com.keep.bdata.TryWithResourceDemo$ExceptionalResource.close(TryWithResourceDemo.java:28)
		at com.keep.bdata.TryWithResourceDemo.demoExceptionalResource(TryWithResourceDemo.java:18)

圖片圖片

5 suppressed exceptions 機(jī)制完整示例代碼

  • suppressed exceptions 機(jī)制的完整示例代碼如下(try-catch-finally ):
package com.keep.bdata;

import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

publicclass SuppressedExceptionsDemo {
    @Test
    public void givenNonExistentFileName_whenAttemptFileOpen_thenNullPointerException() throws IOException {
        demoExceptionWithNoSuppress("/non-existent-path/non-existent-file.txt");
    }
    public static void demoExceptionWithNoSuppress(String filePath) throws IOException {
        FileInputStream fileIn = null;
        try {
            fileIn = new FileInputStream(filePath);
        } catch (FileNotFoundException e) {
            thrownew IOException(e);
        } finally {
            fileIn.close();
        }
    }

    @Test
    public void givenNonExistentFileName_whenAttemptFileOpen_thenNullPointerException_withSuppressed() throws IOException{
        demoExceptionWithSuppressed("/non-existent-path/non-existent-file.txt");
    }
    public static void demoExceptionWithSuppressed(String filePath) throws IOException {
        Throwable firstException = null;
        FileInputStream fileIn = null;
        try {
            fileIn = new FileInputStream(filePath);
        } catch (IOException e) {
            firstException = e;
        } finally {
            try {
                fileIn.close();
            } catch (NullPointerException npe) {
                if (firstException != null) {
                    npe.addSuppressed(firstException);
                }
                throw npe;
            }
        }
    }
}
  • suppressed exceptions 機(jī)制的完整示例代碼如下(try-with-resources 完整示例代碼):
package com.keep.bdata;

import org.junit.jupiter.api.Test;
publicclass TryWithResourceDemo  {
    @Test
    public void givenNonExistentFileName_whenAttemptFileOpen_thenNullPointerException_suppressed() throws Exception {
        demoExceptionalResource();
    }
    public void demoExceptionalResource() throws Exception {
        try (ExceptionalResource exceptionalResource = new ExceptionalResource()) {
            exceptionalResource.processSomething();
        }
    }
    class ExceptionalResource implements AutoCloseable {
        public void processSomething() {
            thrownew IllegalArgumentException("Thrown from processSomething()");
        }
        @Override
        public void close() throws Exception {
            thrownew NullPointerException("Thrown from close()");
        }
    }


責(zé)任編輯:武曉燕 來源: 明哥的IT隨筆
相關(guān)推薦

2017-07-20 16:55:56

Android事件響應(yīng)View源碼分析

2024-06-25 08:18:55

2021-04-07 13:28:21

函數(shù)程序員異步

2013-04-15 10:59:08

iOS開發(fā)ARC版本說明

2022-01-05 10:22:17

HiveAuthenticat認(rèn)證

2025-01-26 15:38:11

Spring事務(wù)編程式

2019-07-23 08:55:46

Base64編碼底層

2015-07-15 17:09:48

HiveHadoop分布式文件系統(tǒng)

2020-10-09 08:15:11

JsBridge

2023-05-08 08:21:15

JavaNIO編程

2021-07-01 10:01:16

JavaLinkedList集合

2024-01-30 09:31:53

SQL語言數(shù)據(jù)庫

2025-03-07 10:04:12

2024-05-10 08:19:59

arthasjava字節(jié)碼

2020-12-29 05:35:43

FlinkSQL排序

2017-09-05 08:52:37

Git程序員命令

2022-02-21 09:44:45

Git開源分布式

2023-05-12 08:19:12

Netty程序框架

2021-06-30 00:20:12

Hangfire.NET平臺

2019-04-17 15:16:00

Sparkshuffle算法
點贊
收藏

51CTO技術(shù)棧公眾號