Java中RuntimeException和Exception的區別

來源:互聯網
上載者:User

標籤:void   dex   todo   字串轉換   一個   string   null對象   一段   處理   

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


所有方法都可以在不聲明throws的情況下拋出RuntimeException及其子類 

不可以在不聲明的情況下拋出非RuntimeException

簡單的說,非RuntimeException要自己寫catch塊處理掉。

 

1.RuntimeException

 

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

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

View Code
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方法的原始碼如下:

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

我們發現這個方法中拋出了NumberFormatException異常,但是在上面的代碼中我們沒有找到try...catch來處理,這是為什麼呢。按照我們異常處理的知識,如果一個方法通過throws拋出了異常,那麼可以在拋出異常的方法中不適用try...catch,但是在調用這個方法的地方必須有try...catch來處理。

下面來觀察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:

1、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;
   }

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

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

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

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

6、UnsupportedOperationException:該操作不被支援。如果我們希望不支援這個方法,可以拋出這個異常。既然不支援還要這個幹嗎?有可能子類中不想支援父類中有的方法,可以直接拋出這個異常。

7、ArithmeticException:算術錯誤,典型的就是0作為除數的時候。

8、IllegalArgumentException:非法參數,在把字串轉換成數位時候經常出現的一個異常,我們可以在自己的程式中好好利用這個異常。

Java中RuntimeException和Exception的區別

聯繫我們

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