<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Java 抑制異常示例 > 原文: [https://howtodoinjava.com/java7/java-suppressed-exceptions/](https://howtodoinjava.com/java7/java-suppressed-exceptions/) 顧名思義, [**被抑制的異常**](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html#suppressed-exceptions "suppressed-exceptions")是在代碼中引發的異常,但是以某種方式被忽略了。 如果您記得[`try-catch-finally`](https://howtodoinjava.com/java7/automatic-resource-management-with-try-with-resources-in-java-7/)塊的執行順序以及它們如何返回任何值或異常,那么您會記得,如果`try`中引發了異常,則也將抑制`finally`塊中引發的**異常**。 在 Java 7 之前的版本中,您通過記錄日志了解了這些異常(如果已實現),但是一旦`finally`塊結束,您就無法控制這些類型的異常。 好吧,借助 Java 7 中的[**新特性**](https://howtodoinjava.com/java7/java-7-changes-features-and-enhancements/ "java 7 features"),您還可以控制這些受抑制的異常。 ```java Table of contents 1\. What are suppressed exceptions? 2\. Suppressed exception example 3\. Demonstration in different scenarios ``` ## 1\. 什么是禁止的異常? 在 Java 7 中,遇到抑制異常的最常見用例是 **try-with-resources** 語句。 當我們在`try`塊中遇到異常時,應用程序將嘗試關閉資源。 如果它遇到關閉`AutoCloseable`資源時可能發生的多個異常,則會將其他異常作為**抑制的異常**附加到主要異常上。 為了支持抑制的異常,在 JDK 7 中向[`Throwable`](https://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html "Throwable")類(`Exception`和`Error`類的父級)添加了新的構造器和兩個新方法。 ```java Throwable.getSupressed(); // Returns Throwable[] Throwable.addSupressed(aThrowable); ``` ## 2\. 抑制異常的例子 例如,在寫入輸出流時,可以從`try`塊引發一個異常,當`try-with-resources`語句嘗試關閉流時,可以從該異常中引發最多兩個異常。 如果從`try`塊引發一個異常,并且從`try-with-resources`語句引發一個或多個異常,則將從`try-with-resources`語句引發的那些異常抑制,并且由該塊引發的異常由`closeStream()`方法拋出。 您可以通過從`try`塊引發的異常中調用`Throwable.getSuppressed()`方法來檢索這些受抑制的異常。 ## 3\. 在不同情況下的示例 例如,我正在編寫一個自動關閉的資源(即`DirtyResource.java`),無論我們嘗試訪問它還是關閉它,它都會引發異常。 這樣,當以不同方式訪問時,我們將能夠看到不同的行為。 ```java public class DirtyResource implements AutoCloseable { /** * Need to call this method if you want to access this resource * @throws RuntimeException no matter how you call this method * */ public void accessResource() { throw new RuntimeException("I wanted to access this resource. Bad luck. Its dirty resource !!!"); } /** * The overridden closure method from AutoCloseable interface * @throws Exception which is thrown during closure of this dirty resource * */ @Override public void close() throws Exception { throw new NullPointerException("Remember me. I am your worst nightmare !! I am Null pointer exception !!"); } } ``` #### 3.1 抑制異常之前的特性 ```java package com.howtodoinjava.demo.core; import static java.lang.System.err; public class SuppressedExceptionDemoWithTryFinallyPrevious { /** * Executable member function demonstrating suppressed exceptions * One exception is lost if not added in suppressed exceptions list */ public static void memberFunction() throws Exception { DirtyResource resource= new DirtyResource(); try { resource.accessResource(); } finally { resource.close(); } } public static void main(String[] arguments) throws Exception { try { memberFunction(); } catch(Exception ex) { err.println("Exception encountered: " + ex.toString()); final Throwable[] suppressedExceptions = ex.getSuppressed(); final int numSuppressed = suppressedExceptions.length; if (numSuppressed > 0) { err.println("tThere are " + numSuppressed + " suppressed exceptions:"); for (final Throwable exception : suppressedExceptions) { err.println("tt" + exception.toString()); } } } } } Output: Exception encountered: java.lang.NullPointerException: Remember me. I am your worst nightmare !! I am Null pointer exception !! ``` 如您所見,僅捕獲了一個異常,而第二個`RuntimeException`被抑制。 #### 3.2 在 Java 7 中抑制異常之后 ```java package com.howtodoinjava.demo.core; import static java.lang.System.err; public class SuppressedExceptionDemoWithTryFinallyNew { /** * Executable member function demonstrating suppressed exceptions * Suppressed expression is added back in primary exception */ public static void memberFunction() throws Exception { Throwable th = null; DirtyResource resource= new DirtyResource(); try { resource.accessResource(); } catch(Exception e) { th = e; } finally { try { resource.close(); } catch(Exception e) { if(th != null) { e.addSuppressed(th); //Add to primary exception throw e; } } } } /** * Executable function demonstrating suppressed exceptions. */ public static void main(String[] arguments) throws Exception { try { memberFunction(); } catch(Exception ex) { err.println("Exception encountered: " + ex.toString()); final Throwable[] suppressedExceptions = ex.getSuppressed(); final int numSuppressed = suppressedExceptions.length; if (numSuppressed > 0) { err.println("tThere are " + numSuppressed + " suppressed exceptions:"); for (final Throwable exception : suppressedExceptions) { err.println("tt" + exception.toString()); } } } } } Output: Exception encountered: java.lang.NullPointerException: Remember me. I am your worst nightmare !! I am Null pointer exception !! There are 1 suppressed exceptions: java.lang.RuntimeException: I wanted to access this resource. Bad luck. Its dirty resource !!! ``` 在這里,在`catch`塊中,我們可以訪問兩個異常。 一個作為主要異常,第二個作為受抑制異常。 #### 3.3 成員函數中的`try-with-resource`塊并捕獲異常 ```java package com.howtodoinjava.demo.core; import static java.lang.System.err; public class SuppressedExceptionDemoWithTryCatch { public static void memberFunction() throws Exception { try (DirtyResource resource= new DirtyResource()) { resource.accessResource(); } } /** * Executable member function demonstrating suppressed exceptions using try-with-resources */ public static void main(String[] arguments) throws Exception { try { memberFunction(); } catch(Exception ex) { err.println("Exception encountered: " + ex.toString()); final Throwable[] suppressedExceptions = ex.getSuppressed(); final int numSuppressed = suppressedExceptions.length; if (numSuppressed > 0) { err.println("tThere are " + numSuppressed + " suppressed exceptions:"); for (final Throwable exception : suppressedExceptions) { err.println("tt" + exception.toString()); } } } } } Output: Exception encountered: java.lang.RuntimeException: I wanted to access this resource. Bad luck. Its dirty resource !!! There are 1 suppressed exceptions: java.lang.NullPointerException: Remember me. I am your worst nightmare !! I am Null pointer exception !! ``` 太好了! 在成員函數中使用`try-with-resource`時,我們能夠看到這兩種異常。 #### 3.4 默認`try-with-resource`塊 ```java package com.howtodoinjava.demo.core; public class SuppressedExceptionDemoWithTryWithResource { /** * Demonstrating suppressed exceptions using try-with-resources */ public static void main(String[] arguments) throws Exception { try (DirtyResource resource= new DirtyResource()) { resource.accessResource(); } } } Output: Exception in thread "main" java.lang.RuntimeException: I wanted to access this resource. Bad luck. Its dirty resource !!! at DirtyResource.accessResource(DirtyResource.java:9) at SuppressedExceptionDemoWithTryWithResource.main(SuppressedExceptionDemoWithTryWithResource.java:12) Suppressed: java.lang.NullPointerException: Remember me. I am your worst nightmare !! I am Null pointer exception !! at DirtyResource.close(DirtyResource.java:19) at SuppressedExceptionDemoWithTryWithResource.main(SuppressedExceptionDemoWithTryWithResource.java:13) ``` 好吧,非常高興看到包含**抑制異常**的完整信息的輸出。 學習愉快!
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看