Thinking in Java——筆記(12)

来源:http://www.cnblogs.com/apolloqq/archive/2016/12/12/6165820.html
-Advertisement-
Play Games

Error Handling with Exceptions ___ The ideal time to catch an error is at compile time, before you even try to run the program. The rest of the proble ...


Error Handling with Exceptions


  • The ideal time to catch an error is at compile time, before you even try to run the program.
  • The rest of the problems must be handled at run time through some formality that allows the originator of the error to pass appropriate information to a recipient who will know how to handle the difficulty properly.
  • To create a robust system, each component must be robust.
  • By providing a consistent error-reporting model using exceptions, Java allows components to reliably communicate problems to client code.

Concepts

  • At the point where the problem occurs, you might not know what to do with it, but you do know that you can’t just continue on merrily.
  • You don’t have enough information in the current context to fix the problem. So you hand the problem out to a higher context where someone is qualified to make the proper decision.
  • You only need to handle the problem in one place, in the so-called exception handler.

Basic exceptions

  • With an exceptional condition, you cannot continue processing because you don’t have the information necessary to deal with the problem in the current context.
  • All you can do is jump out of the current context and relegate that problem to a higher context. This is what happens when you throw an exception.
  • You can send information about the error into a larger context by creating an object representing your information and "throwing" it out of your current context. This is called throwing an exception.
  • Exceptions allow you to think of everything that you do as a transaction, and the exceptions guard those transactions.
  • Exceptions allow you to (if nothing else) force the program to stop and tell you what went wrong, or (ideally) force the program to deal with the problem and return to a stable state.

Exception arguments

  • There are two constructors in all standard exceptions: The first is the default constructor, and the second takes a string argument so that you can place pertinent information in the exception.
  • After creating an exception object with new, you give the resulting reference to throw.
  • A simplistic way to think about exception handling is as a different kind of return mechanism.
  • You can throw any type of Throwable, which is the exception root class.

Catching an exception

  • guarded region is a section of code that might produce exceptions and is followed by the code to handle those exceptions.

The try block

  • If you don’t want a throw to exit the method, you can set up a special block within that method to capture the exception.
  • With exception handling, you put everything in a try block and capture all the exceptions in one place.

Exception handlers

  • The thrown exception must end up someplace. This "place" is the exception handler.
  • Sometimes you never use the identifier because the type of the exception gives you enough information to deal with the exception.
  • If an exception is thrown, the exception-handling mechanism goes hunting for the first handler with an argument that matches the type of the exception.

Termination vs. resumption

  • termination: you assume that the error is so critical that there’s no way to get back to where the exception occurred.
  • resumption: the exception handler is expected to do something to rectify the situation, and then the faulting method is retried, presuming success the second time.
  • If you want resumption-like behavior in Java, don’t throw an exception when you encounter an error.
  • Although resumption sounds attractive at first, it isn’t quite so useful in practice.

Creating your own exceptions

  • The most trivial way to create a new type of exception is just to let the compiler create the default constructor for you.
  • The most important thing about an exception is the class name.
  • If you send output to System.err, it will not be redirected along with System.out so the user is more likely to notice it.

Exceptions and logging

  • It’s more common that you will be catching and logging someone else’s exception, so you must generate the log message in the exception handler.
  • All this dressing-up might be lost on the client programmers using your packages, since they might simply look for the exception to be thrown and nothing more.

The exception specification

  • exception specification: Java provides syntax (and forces you to use that syntax) to allow you to politely tell the client programmer what exceptions this method throws.
  • You must either handle the exception or indicate with an exception specification that it may be thrown from your method.
  • You can actually start throwing the exception later without requiring changes to existing code.
  • Exceptions that are checked and enforced at compile time are called checked exceptions.

Catching any exception

  • Since the Exception class is the base of all the exception classes that are important to the programmer, you don’t get much specific information about the exception, but you can call the methods that come from its base type Throwable.

The stack trace

  • getStackTrace( ) method returns an array of stack trace elements, each representing one stack frame.

Rethrowing an exception

  • Rethrowing an exception causes it to go to the exception handlers in the nexthigher context.
  • Everything about the exception object is preserved, so the handler at the higher context that catches the specific exception type can extract all the information from that object.
  • It’s also possible to rethrow a different exception from the one you caught.
  • You never have to worry about cleaning up the previous exception, or any exceptions for that matter.

Exception chaining

  • exception chainin: you want to catch one exception and throw another, but still keep the information about the originating exception.
  • The cause is intended to be the originating exception, and by passing it in you maintain the stack trace back to its origin.

Standard Java exceptions

  • There are two general types of Throwable objects.
  • Error represents compile-time and system errors that you don’t worry about catching.
  • Exception is the basic type that can be thrown from any of the standard Java library class methods and from your methods and runtime accidents.

Special case: RuntimeException

  • If any call is made to a null reference, Java will automatically throw a NullPointerException.
  • You never need to write an exception specification saying that a method might throw a RuntimeException, because they are unchecked exceptions.
  • A RuntimeException(or anything inherited from it) is a special case, since the compiler doesn’t require an exception specification for these types.
  • A RuntimeException represents a programming error.

Performing cleanup with finally

  • There’s often some piece of code that you want to execute whether or not an exception is thrown within a try block.
  • Exceptions in Java do not allow you to resume back to where the exception was thrown.

What’s finally for?

  • finally is important because it allows the programmer to guarantee the release of memory regardless of what happens in the try block.
  • The finally clause is necessary when you need to set something other than memory back to its original state.
  • Along with the labeled break and labeled continue, finally eliminates the need for a goto statement in Java.

Using finally during return

  • Because a finally clause is always executed, it’s possible to return from multiple points within a method and still guarantee that important cleanup will be performed.

Pitfall: the lost exception

  • It’s possible for an exception to simply be lost. This happens with a particular configuration using a finally clause.
  • Using ‘return’ inside the finally block will silence any thrown exception.

Exception restrictions

  • When you override a method, you can throw only the exceptions that have been specified in the base-class version of the method.
  • Interface CANNOT add exceptions to existing methods from the base class, this makes sense because otherwise you’d never know if you were catching the correct thing when working with the base class.
  • The restriction on exceptions does not apply to constructors.
  • The derived-class constructor must declare any base-class constructor exceptions in its exception specification.
  • By forcing the derived-class methods to conform to the exception specifications of the base-class methods, substitutability of objects is maintained.
  • A derived-class version of a method may choose not to throw any exceptions, even if the base-class version does.
  • The exception specifications are not part of the type of a method, which comprises only the method name and argument types.
  • The "exception specification interface" for a particular method may narrow during inheritance and overriding, but it may not widen.

Constructors

  • If you throw an exception from inside a constructor, these cleanup behaviors might not occur properly.
  • If a constructor fails partway through its execution, it might not have successfully created some part of the object that will be cleaned up in the finally clause.
  • One of the design issues with exceptions is whether to handle an exception completely at this level, to handle it partially and pass the same exception (or a different one) on, or whether to simply pass it on.
  • The basic rule is: Right after you create an object that requires cleanup, begin a try-finally.

Exception matching

  • When it finds a match, the exception is considered handled, and no further searching occurs.
  • Matching an exception doesn’t require a perfect match between the exception and its handler.
  • If you decide to add more derived exceptions to a method, then the client programmer’s code will not need changing as long as the client catches the base-class exceptions.

Alternative approaches

  • It’s worth observing that the issue of programmer convenience in handling errors was a prime motivation for exceptions in the first place.
  • One of the important goals of exception handling is to move the error-handling code away from the point where the errors occur.
  • Exception handling also tends to reduce the amount of error-handling code, by allowing one handler to deal with many error sites.
  • Because the compiler forces you to write code right away to handle the exception, this seems like the easiest solution even though it’s probably the worst thing you can do.

History

  • To draw them into a better way of handling errors, the amount of code they would need to "add" must not be onerous.
  • The exception specification really has two purposes.
  • In C++, no compile-time checking occurs to determine whether or not the function or method will actually throw that exception, or whether the exception specification is complete.
  • In Java, there are restrictions on the way that Java generics can be used with exception specifications.

Perspectives

  • Java’s important step was to unify the error-reporting model, so that all errors are reported using exceptions.
  • When Java modified the C++ model so that exceptions were the only way to report errors, the extra enforcement of checked exceptions may have become less necessary.
  • It’s even more important to realize the limitation of what the compiler is able to do.
  • In any event, the likelihood of checked exceptions ever being removed from Java seems dim.
  • However, if you find that some checked exceptions are getting in your way, or especially if you find yourself being forced to catch exceptions, but you don’t know what to do with them, there are some alternatives.

Passing exceptions to the console

  • Note that main( ) is also a method that may have an exception specification.
  • By passing it out to the console, you are relieved from writing try-catch clauses within the body of main( ).

Converting checked to unchecked exceptions

  • You simply "wrap" a checked exception inside a RuntimeException by passing it to the RuntimeException constructor.
    

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 準備篇: 1、配置防火牆,開啟80埠、3306埠 vi /etc/sysconfig/iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT(允許80埠通過防火牆) -A INPUT -m state ...
  • 第一篇博客。 克魯斯卡爾求最小生成樹思想:首先將n個點看做n個獨立的集合,將所有邊快排(從小到大)。然後,按排好的順序枚舉每一條邊,判斷這條邊連接的兩個點是否屬於一個集合。若是,則將這條邊加入最小生成樹,並將兩個點所在的集合合併為一個集合。若否,則跳過。直到找到n-1條邊為止。 #include<i ...
  • 這個系統是南方七星彩投註網站系統源碼,網站是採用php+MySQL的。基本實現功能如下:這個是普通的七星前四位的網投註平臺股東-總代理-代理-會員 這四個級別 網站大家只限於學習與交流,並且在合法的範圍使用,為了防止系統其他用戶,代碼有進行加密了,不便多多瞭解。 投註網站源碼附件: http://f ...
  • 對於一個有登錄限制(許可權限制)的網站,用戶輸入身份驗證信息以後,驗證成功後跳轉到登錄前的頁面是一項很人性化的功能。那麼獲取登錄前的頁面地址就很關鍵,今天在做一個yii2項目的登錄調試時發現了一些很有意思的問題,記錄下來。 1,場景描述 網站SiteA上的頁面Page2需要登錄後才能查看,Page2的 ...
  • ...
  • 列印一排*,很簡單,列印下圖 也很簡單,代碼如下: 可是昨天想了好久都沒想到怎樣做到下麵圖片的樣子,今天突然就有了靈感 代碼很簡單,就是昨天想破了腦袋都想不出來,好笨啊我 第一行列印一個*,第二行行列印兩個*,大三行列印三個*,這樣分析就找到規律了,定義一個a=1,外層迴圈實現列印幾行,定義一個i= ...
  • 上面的代碼是段合法的cpp代碼嗎? 答案當然是是的. 這些 問號 是個什麼鬼?它們就是cpp標準中定義的 "Trigraph(MS)" .之所以出現這些神奇的符號,主因主要是字元集的問題.簡單來說可以理解為某些老外的鍵盤沒有"{","|","\"這些符號.所以需要用這種類似"轉義字元"的東東來表達c ...
  • KMP演算法是字元串模式匹配當中最經典的演算法,原來大二學數據結構的有講,但是當時只是記住了原理,但不知道代碼實現,今天終於是完成了KMP的代碼實現。原理KMP的原理其實很簡單,給定一個字元串和一個模式串,然後找模式串在給定字元串中的位置。將兩個字元串轉換為字元數組,然後從兩個數組的開始位置"i","j ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...