常見的RuntimeException

常見的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:非法參數,在把字符串轉換成數字的時候經常出現的一個異常,我們可以在自己的程序中好好利用這個異常。

 

IT視頻教程集合:http://blog.sina.com.cn/s/blog_189450fd80102xp2f.html

原文地址:https://blog.csdn.net/qq_25166683/article/details/81131579

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章