java中的異常詳解

來源:互聯網
上載者:User

標籤:java   jdk   異常   exception   程式員   

java中的exception關係圖所示:

Throwable是Exception(異常)和Error(錯誤)的超類!!

兩者的區別:

Exception表示程式需要捕捉和處理的的異常;

Error表示系統層級的錯誤和程式無需處理的。

我們日常程式中所遇到的是Exception,Exception分為兩種:

第一種是JDK標準內建的異常,當程式違反了jdk的文法規則或者非法使用記憶體等,程式就會拋出異常,常見的jdk異常有:

java.lang.nullpointerexception,
java.lang.classnotfoundexception
java.lang.arrayindexoutofboundsexception
java.lang.filenotfoundexception
等等。。。
第二種是程式員自己定義的異常,程式員可以建立自己的異常,並自由選擇在何時用throw關鍵字引發異常。
所有的異常都是Thowable的子類。


java中ERROR和EXCEPTION的區別

error繼承父類java.lang.Error,而exception繼承java.lang.Exception.EXCEPTION和ERROR都繼承java.lang.Throwable,可以說,error和exception叔輩兄弟的關係

jdk中對ERROR和EXCEPTION的解釋

java.lang.Error: An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. ERROR用於標記嚴重錯誤。合理的應用程式不應該去try/catch這種錯誤!!!

java.lang.Exception: The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch. 即Exception用於指示一種合理的程式想去catch的條件。即它僅僅是一種程式運行條件,而非嚴重錯誤,並且鼓勵使用者程式去catch它。


最後上傳一個exception的demo:

package com.panther.dong.exception;/** * Created by panther on 15-8-2. */class MyException extends Exception {    public void f() {        System.out.println("this is my exception");    }}public class DemoException {    private int i = 0;    private int j;    DemoException(int x) throws MyException {        f2();        j = x / i;    }    public void f2() throws MyException {        System.out.println("this is My first Exception");        throw new MyException();    }    public static void main(String[] args) {        System.out.println("-----------Exception-------------");        try {            new DemoException(9);        } catch (MyException e) {            e.f();        } catch (Exception e) {            e.printStackTrace();        } finally {            System.out.println("finally is first Exception");        }        System.out.println("---------------------------------");        try {            throw new MyException();        } catch (MyException e) {            e.f();        } finally {            System.out.println("finally is second Exception");        }        System.out.println("--------------程式結束-------------");    }}

運行結果:


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

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.