Java中RuntimeException和Exception的區別

Java的異常類體系中,Error和RuntimeException是非檢查型異常,其餘的都是檢查型異常。java


全部方法均可以在不聲明throws的狀況下拋出RuntimeException及其子類 

不能夠在不聲明的狀況下拋出非RuntimeException

簡單的說,非RuntimeException要本身寫catch塊處理掉。數組

 

1.RuntimeException

 

今天摩根IT電面的時候被問到Exception和RuntimeException的區別,當時答不出來,大囧,晚上來學習一下。學習

首先看一段代碼,主要內容就是將字符串類型的數字轉化爲整型的數字,而後讓兩個數字相乘,代碼以下:spa

View Code.net

public class RuntimeException {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String str="123";
        int temp=Integer.parseInt(str);
        System.out.println(temp*temp);
    }
}

產看parseInt方法的源代碼以下:orm

View Code對象

public static int parseInt(String s) throws NumberFormatException {
    return parseInt(s,10);
    }

咱們發現這個方法中拋出了NumberFormatException異常,可是在上面的代碼中咱們沒有找到try...catch來處理,這是爲何呢。按照咱們異常處理的知識,若是一個方法經過throws拋出了異常,那麼能夠在拋出異常的方法中不適用try...catch,可是在調用這個方法的地方必須有try...catch來處理。blog

下面來觀察NumberFormatException類的繼承關係:繼承

從上圖咱們能夠發現NumberFormatException是RuntimeException的子類,那麼這就須要咱們清楚Exception和RuntimeException的概念:開發

  1. Exception:在程序中必須使用try...catch進行處理。
  2. RuntimeException:能夠不使用try...catch進行處理,可是若是有異常產生,則異常將由JVM進行處理。

對於RuntimeException的子類最好也使用異常處理機制。雖然RuntimeException的異常能夠不使用try...catch進行處理,可是若是一旦發生異常,則確定會致使程序中斷執行,因此,爲了保證程序再出錯後依然能夠執行,在開發代碼時最好使用try...catch的異常處理機制進行處理。

2.User Defined Exception

下面給出一個自定義異常的實例:

View Code

class MyException extends Exception{
    public MyException(String msg){
        super(msg);
    }
}

public class DefaultException {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try{
            throw new MyException("自定義異常");
        }catch(Exception e){
            System.out.println(e);//edu.sjtu.ist.comutil.MyException: 自定義異常
            //System.err.println(e);
//            e.printStackTrace();
//            StackTraceElement[] sts = e.getStackTrace();
//            for (StackTraceElement st : sts){
//                System.err.println(st);
//            }

        //    System.err.println(e.getStackTrace());
        }

    }

}

輸出結果爲:

MyException: 自定義異常

 

 

常見的RuntimeException- -

 

                                      

RuntimeException是開發中最容易遇到的,下面列舉一下常見的RuntimeException:

一、NullPointerException:見的最多了,其實很簡單,通常都是在null對象上調用方法了。
      String s=null;
      boolean eq=s.equals(""); // NullPointerException
   這裏你看的很是明白了,爲何一到程序中就暈呢?
   public int getNumber(String str){
  if(str.equals("A")) return 1;
   else if(str.equals("B")) return 2;
   }
   這個方法就有可能拋出NullPointerException,我建議你主動拋出異常,由於代碼一多,你可能又暈了。
   public int getNumber(String str){
  if(str==null) throw new NullPointerException("參數不能爲空");
                                   //你是否以爲明白多了
  if(str.equals("A")) return 1;
      else if(str.equals("B")) return 2;
   }

二、NumberFormatException:繼承IllegalArgumentException,字符串轉換爲數字時出現。好比int i= Integer.parseInt("ab3");

三、ArrayIndexOutOfBoundsException:數組越界。好比 int[] a=new int[3]; int b=a[3];

四、StringIndexOutOfBoundsException:字符串越界。好比 String s="hello"; char c=s.chatAt(6);

五、ClassCastException:類型轉換錯誤。好比 Object obj=new Object(); String s=(String)obj;

六、UnsupportedOperationException:該操做不被支持。若是咱們但願不支持這個方法,能夠拋出這個異常。既然不支持還要這個幹嘛?有可能子類中不想支持父類中有的方法,能夠直接拋出這個異常。

七、ArithmeticException:算術錯誤,典型的就是0做爲除數的時候。

八、IllegalArgumentException:非法參數,在把字符串轉換成數字的時候常常出現的一個異常,咱們能夠在本身的程序中好好利用這個異常。

相關文章
相關標籤/搜索