java基礎---->Java中異常的使用(二)

來源:互聯網
上載者:User

標籤:style   color   rgs   建立   before   static   exe   str   public   

  這一篇部落格用例子講述一下異常的處理過程。

異常的執行過程一、執行個體一:return語句
public class ExceptionTest_1 {    public static void main(String[] args) {        int result = 0;        try {            System.out.println("before result");            result = 9 / 0;            System.out.println("after result");        } catch (Exception e) {            System.out.println("exception" + e.getMessage() + ", result: " + result);            return;        } finally {            System.out.println("final execute, " + result);        }        System.out.println("out of try statement, " + result);    }}

執行的結果如下:

before resultexception/ by zero, result: 0final execute, 0

將上述代碼result = 9 / 0改為 result = 9 / 2;也就是不產生異常,執行的結果如下:

before resultafter resultfinal execute, 4out of try statement, 4

 

二、執行個體二:try裡面有try語句
public class ExceptionTest_2 {    public static void main(String[] args) {        try {            if (1 + 2 > 2) {                throw new FileNotFoundException();            }            try {                throw new FileNotFoundException();            } catch (FileNotFoundException e) {                System.out.println("world hello");            }        } catch (Exception e) {            System.out.println("hello world");        } finally {            System.out.println("final action");        }    }}

執行的結果如下:

hello worldfinal action

如果將if(1 + 2 > 2)改變if(1 + 2 > 4),也就是try塊裡面沒有拋出異常。執行的結果如下:

world hellofinal action

 簡短的異常說明:

當拋出異常後,會發生以下的事情。1、用new在堆上建立異常對象,當前的執行路徑被終止,並從當前環境中彈出異常對象的引用。2、異常處理機制接管程式,並尋找一個恰當的地方繼續執行程式。3、如果有定義了final,那麼會執行final塊的代碼。

 

友情連結
  • 詳細的異常說明:http://blog.csdn.net/hguisu/article/details/6155636

 

java基礎---->Java中異常的使用(二)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.