Java常見的10個異常


1、NullPointerException:

  空指針異常,當操作一個 null 對象的方法或屬性時會拋出這個異常。是一個很頭疼的異常,因為它是運行時異常,不需要手動捕獲,但運行時碰到這個異常會中斷程序。

2、OutOfMemoryError:

  內存溢出異常,這不是程序能控制的,當需要分配的對象的內存超出了當前最大的堆內存,需要調整堆內存大小(-Xmx)以及優化程序。

3、IOException:

  IO,即:Input、Output,我們在讀寫磁盤文件、網絡內容的時候經常會生的一種異常,這種異常是受檢查異常,需要進行手工捕獲。

比如讀寫文件是需要拋出異常:

public int read() throws IOException
public void write(int b) throws IOException

4、FileNotFoundException:

  找不到文件異常,如果文件不存在就會拋出這種異常。

如定義輸入輸出文件流,文件不存在會報錯:

public FileInputStream(File file) throws FileNotFoundException
public FileOutputStream(File file) throws FileNotFoundException

FileNotFoundException 其實是 IOException 的子類,同樣是受檢查異常,需要進行手工捕獲。

5、ClassNotFoundException:

  類找不到異常,Java開發中經常遇到的一種異常,這是在加載類的時候拋出來的,即在類路徑下不能加載指定的類。它是受檢查異常,需要進行手工捕獲。

public static <T> Class<T> getExistingClass(ClassLoader classLoader, String className) {
  try {
     return (Class<T>) Class.forName(className, true, classLoader);
  }
  catch (ClassNotFoundException e) {
     return null;
  }
}

6、ClassCastException:

  類轉換異常,將一個不是該類的實例轉換成這個類就會拋出這個異常。

如將一個數字強制轉換成字符串就會報這個異常:

Object x = new Integer(0);
System.out.println((String)x);

它是運行時異常,不需要手工捕獲。

7、NoSuchMethodException:

沒有這個方法異常,一般發生在反射調用方法的時候:

public Method getMethod(String name, Class<?>... parameterTypes)
    throws NoSuchMethodException, SecurityException {
    checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
    Method method = getMethod0(name, parameterTypes, true);
    if (method == null) {
        throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
    }
    return method;
}

它是受檢查異常,需要手工捕獲。

8、IndexOutOfBoundsException:

索引越界異常,當操作一個字符串或者數組的時候經常遇到的異常。

如圖所示,它是運行時異常,不需要手工捕獲。

9、ArithmeticException:

算術異常,發生在數字的算術運算時的異常,如一個數字除以 0 就會報這個錯。

此異常雖然是運行時異常,可以手工捕獲拋出自定義的異常,如:

public static Timestamp from(Instant instant) {
    try {
        Timestamp stamp = new Timestamp(instant.getEpochSecond() * MILLIS_PER_SECOND);
        stamp.nanos = instant.getNano();
        return stamp;
    } catch (ArithmeticException ex) {
        throw new IllegalArgumentException(ex);
    }
}

10、SQLException:

SQL異常,發生在操作數據庫時的異常。

如下面的獲取數據庫連接時:

public Connection getConnection() throws SQLException {
    if (getUser() == null) {
        return DriverManager.getConnection(url);
    } else {
        return DriverManager.getConnection(url, getUser(), getPassword());
    }
}

它是受檢查異常,需要進行手工捕獲。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM