Java中Error捕獲深入

來源:互聯網
上載者:User

Java Error能不能捕獲這個問題,之前從別人的部落格看到過,然後自己也實驗過,其實Error和Exception一樣是可以捕獲的。但是前些時候,又開始和同事討論了起來,相比之前別人的文章,只是驗證可以捕獲,想加入點不同的東西。所以寫下這篇文章。
首先下面的代碼就是出現異常並捕獲的代碼。

private static void testCatchError() {try {throw new Error("An error occurs here");} catch (Exception e) {System.out.println("catched as Exception");e.printStackTrace();} catch (Error e) {System.out.println("catched as Error");e.printStackTrace();} catch (Throwable t) {System.out.println("catched as Throwable");t.printStackTrace();}System.out.println("reach the end of the method");}

運行這個方法,日誌出現了。

java.lang.Error: An error occurs hereat ps.androidyue.catcherror.MainRoot.testCatchError(MainRoot.java:10)at ps.androidyue.catcherror.MainRoot.main(MainRoot.java:5)catched as Errorreach the end of the method

從上面的日誌我們可以很明確的分析出來,我們throw出的Error對象,沒有經過Exception的catch,而是進入了Error的catch並成功捕獲,進而可以向下執行到末尾的輸出。
那麼Error比Exception的層級高還是兩者並列?後面的Throwable又是什麼呢
首先我們瞭解一下Throwable,從javadoc可以看出是VM可以拋出的對象執行個體的超類,Error和Exception是並列的關係。比如我們常常調用的exception.printStackTrace() 就是Throwable中的。

/** * The superclass of all classes which can be thrown by the VM. The * two direct subclasses are recoverable exceptions ({@code Exception}) and * unrecoverable errors ({@code Error}). This class provides common methods for * accessing a string message which provides extra information about the * circumstances in which the {@code Throwable} was created (basically an error * message in most cases), and for saving a stack trace (that is, a record of * the call stack at a particular point in time) which can be printed later. * <p> * A {@code Throwable} can also include a cause, which is a nested {@code * Throwable} that represents the original problem that led to this {@code * Throwable}. It is often used for wrapping various types of errors into a * common {@code Throwable} without losing the detailed original error * information. When printing the stack trace, the trace of the cause is * included. * * @see Error * @see Exception * @see RuntimeException */public class Throwable implements java.io.Serializable {//code goes here}

Exception的部分代碼

/** * {@code Exception} is the superclass of all classes that represent recoverable * exceptions. When exceptions are thrown, they may be caught by application * code. * * @see Throwable * @see Error * @see RuntimeException */public class Exception extends Throwable {//code goes here}

Error的部分代碼

/** * {@code Error} is the superclass of all classes that represent unrecoverable * errors. When errors are thrown, they should not be caught by application * code. * * @see Throwable * @see Exception * @see RuntimeException */public class Error extends Throwable {//code goes here}

那麼我們可以使用try-catch捕獲異常,錯誤,亦或者使用從更大層面捕獲Throwable,這一點是不可取的。我們使用try-catch捕獲異常是可以,因為這些異常一般是Application code產生的。但是像錯誤不應該被程式碼捕獲。極個別的除外,比如說OutOfMemoryError.

那麼為什麼有點異常需要強制使用try-catch,有的則不需要?
java中有兩種大類型的異常,一種是RuntimeException,另一種是非RuntimeException。

RuntimeException是unchecked的異常,不需要使用try-catch

常見的RuntimeException有NullPointerException等
而非RuntimeException是checked異常,需要使用try-catch 來check

還有一個問題,就是關於Exception是recoverable,而Error是unrecoverable這個目前不是很清楚,下來研究另文說明。

推薦相關文章閱讀:http://learnwithharsha.com/exceptions/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.