標籤: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中的異常詳解