<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>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                ## Chapter 10. Exceptions(異常) ### Item 71: Avoid unnecessary use of checked exceptions(避免不必要地使用 checked 異常) Many Java programmers dislike checked exceptions, but used properly, they can improve APIs and programs. Unlike return codes and unchecked exceptions, they force programmers to deal with problems, enhancing reliability. That said, overuse of checked exceptions in APIs can make them far less pleasant to use. If a method throws checked exceptions, the code that invokes it must handle them in one or more catch blocks, or declare that it throws them and let them propagate outward. Either way, it places a burden on the user of the API. The burden increased in Java 8, as methods throwing checked exceptions can’t be used directly in streams (Items 45–48). 許多 Java 程序員不喜歡 checked 異常,但是如果使用得當,它們可以有利于 API 和程序。與返回代碼和 unchecked 異常不同,它們強制程序員處理問題,提高了可靠性。相反,在 API 中過度使用 checked 異常會變得不那么令人愉快。如果一個方法拋出 checked 異常,調用它的代碼必須在一個或多個 catch 塊中處理它們;或者通過聲明拋出,讓它們向外傳播。無論哪種方式,它都給 API 的用戶帶來了負擔。Java 8 中,這一負擔增加得更多,因為會拋出 checked 異常的方法不能直接在流(Item 45-48)中使用。 This burden may be justified if the exceptional condition cannot be prevented by proper use of the API and the programmer using the API can take some useful action once confronted with the exception. Unless both of these conditions are met, an unchecked exception is appropriate. As a litmus test, ask yourself how the programmer will handle the exception. Is this the best that can be done? 如果(1)正確使用 API 也不能防止異常情況,(2)并且使用 API 的程序員在遇到異常時可以采取一些有用的操作,那么這種負擔是合理的。除非滿足這兩個條件,否則可以使用 unchecked 異常。作為程序能否成功的試金石,程序員應該問問自己將如何處理異常。這是最好的辦法嗎? ``` } catch (TheCheckedException e) { throw new AssertionError(); // Can't happen! } ``` Or this? 或者這樣? ``` } catch (TheCheckedException e) { e.printStackTrace(); // Oh well, we lose. System.exit(1); } ``` If the programmer can do no better, an unchecked exception is called for. 如果程序員不能做得更好,則需要一個 unchecked 異常。 The additional burden on the programmer caused by a checked exception is substantially higher if it is the sole checked exception thrown by a method. If there are others, the method must already appear in a try block, and this exception requires, at most, another catch block. If a method throws a single checked exception, this exception is the sole reason the method must appear in a try block and can’t be used directly in streams. Under these circumstances, it pays to ask yourself if there is a way to avoid the checked exception. 如果 checked 異常是方法拋出的唯一 checked 異常,那么 checked 異常給程序員帶來的額外負擔就會大得多。如果還有其他 checked 異常,則該方法一定已經在 try 塊中了,因此該異常最多需要另一個 catch 塊而已。如果一個方法拋出單個 checked 異常,那么這個異常就是該方法必須出現在 try 塊中而不能直接在流中使用的唯一原因。在這種情況下,有必要問問自己是否有辦法避免 checked 異常。 The easiest way to eliminate a checked exception is to return an optional of the desired result type (Item 55). Instead of throwing a checked exception, the method simply returns an empty optional. The disadvantage of this technique is that the method can’t return any additional information detailing its inability to perform the desired computation. Exceptions, by contrast, have descriptive types, and can export methods to provide additional information (Item 70). 消除 checked 異常的最簡單方法是返回所需結果類型的 Optional 對象([Item-55](/Chapter-8/Chapter-8-Item-55-Return-optionals-judiciously.md))。該方法只返回一個空的 Optional 對象,而不是拋出一個 checked 異常。這種技術的缺點是,該方法不能返回任何詳細說明其無法執行所需計算的附加信息。相反,異常具有描述性類型,并且可以導出方法來提供附加信息([Item-70](/Chapter-10/Chapter-10-Item-70-Use-checked-exceptions-for-recoverable-conditions-and-runtime-exceptions-for-programming-errors.md))。 You can also turn a checked exception into an unchecked exception by breaking the method that throws the exception into two methods, the first of which returns a boolean indicating whether the exception would be thrown. This API refactoring transforms the calling sequence from this: 你還可以通過將拋出異常的方法拆分為兩個方法,從而將 checked 異常轉換為 unchecked 異常,第一個方法返回一個布爾值,指示是否將拋出異常。這個 API 重構將調用序列轉換為: ``` // Invocation with checked exception try { obj.action(args); } catch (TheCheckedException e) { ... // Handle exceptional condition } ``` into this: 轉換為這種形式: ``` // Invocation with state-testing method and unchecked exception if (obj.actionPermitted(args)) { obj.action(args); } else { ... // Handle exceptional condition } ``` This refactoring is not always appropriate, but where it is, it can make an API more pleasant to use. While the latter calling sequence is no prettier than the former, the refactored API is more flexible. If the programmer knows the call will succeed, or is content to let the thread terminate if it fails, the refactoring also allows this trivial calling sequence: 這種重構并不總是適當的,但是只要在適當的地方,它就可以使 API 更易于使用。雖然后一種調用序列并不比前一種調用序列漂亮,但是經過重構的 API 更加靈活。如果程序員知道調用會成功,或者不介意由于調用失敗而導致的線程終止,那么該重構還可以接受更簡單的調用序列: ``` obj.action(args); ``` If you suspect that the trivial calling sequence will be the norm, then the API refactoring may be appropriate. The resulting API is essentially the state-testing method API in Item 69 and the same caveats apply: if an object is to be accessed concurrently without external synchronization or it is subject to externally induced state transitions, this refactoring is inappropriate because the object’s state may change between the calls to actionPermitted and action. If a separate actionPermitted method would duplicate the work of the action method, the refactoring may be ruled out on performance grounds. 如果你不認為上文更簡單的調用序列是一種常態,那么 API 重構可能是合適的。重構之后的 API 在本質上等同于 [Item-69](/Chapter-10/Chapter-10-Item-69-Use-exceptions-only-for-exceptional-conditions.md) 中的「狀態測試」方法,并且,也有同樣的告誡:如果對象將在缺少外部同步的情況下被并發訪問,或者可被外界改變狀態,這種重構就是不恰當的,因為在 actionPermitted 和 action 這兩個調用的間隔,對象的狀態有可能會發生變化。如果單獨的 actionPermitted 方法必須重復 action 方法的工作,出于性能的考慮,這種 API 重構就不值得去做。 In summary, when used sparingly, checked exceptions can increase the reliability of programs; when overused, they make APIs painful to use. If callers won’t be able to recover from failures, throw unchecked exceptions. If recovery may be possible and you want to force callers to handle exceptional conditions, first consider returning an optional. Only if this would provide insufficient information in the case of failure should you throw a checked exception. 總之,如果謹慎使用,checked 異常可以提高程序的可靠性;當過度使用時,它們會使 API 難以使用。如果調用者不應從失敗中恢復,則拋出 unchecked 異常。如果恢復是可能的,并且你希望強制調用者處理異常條件,那么首先考慮返回一個 Optional 對象。只有當在失敗的情況下,提供的信息不充分時,你才應該拋出一個 checked 異常。 --- **[Back to contents of the chapter(返回章節目錄)](/Chapter-10/Chapter-10-Introduction.md)** - **Previous Item(上一條目):[Item 70: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors(對可恢復情況使用 checked 異常,對編程錯誤使用運行時異常)](/Chapter-10/Chapter-10-Item-70-Use-checked-exceptions-for-recoverable-conditions-and-runtime-exceptions-for-programming-errors.md)** - **Next Item(下一條目):[Item 72: Favor the use of standard exceptions(鼓勵復用標準異常)](/Chapter-10/Chapter-10-Item-72-Favor-the-use-of-standard-exceptions.md)**
                  <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>

                              哎呀哎呀视频在线观看