JVM在遇到異常時會幹什麼
- JVM會根據異常產生原因創建一個對象,這個對象包括了異常產生的(內容,原因,位置)。
- 在方法中若沒有異常處理邏輯那麼JVM就會把異常類對象拋出給方法的調用者main方法來處理這個異常
- main方法接收到了這個異常對象,main方法也沒有異常處理邏輯繼續把對象拋出給main方法的調用者JVM處理這個異常
- JVM接收到這個異常後做了兩件事情:
- 把異常對象(內容原因位置)以紅色字體打印到控制檯
- JVM會終止當前正在執行的Java程序–>中斷處理
非法參數異常(java.lang.IllegalArgumentException)
原因:使用set.of後添加元素不能是重複的
Set<String> set = Set.of("a", "b", "c","a");
System.out.println(set);
不支持操作異常(java.lang.UnsupportedOperationException)
原因:使用list.of後元素不能添加數據。set,Map也同樣不能添加
List<String> a = List.of("a", "b", "c");
System.out.println(a);
//拋出異常
a.add("w");
數組越界異常java.lang.ArrayIndexOutOfBoundsException
原因:訪問的索引超出數組的索引
public class Demo01Exception {
public static void main(String[] args) {
int[] arr = {1,2,3,4};
//拋出異常
int ele = getElement(4, arr);
System.out.println(ele);
}
/*定義一個方法獲取數組索引處的元素*/
private static int getElement(int index, int[] arr) {
int i = arr[index];
return i;
}
}
獲取線程異常java.util.concurrent.RejectedExecutionException
原因:shutdown銷燬了線程池之後就不能再獲取線程池了
public class Demo01ThreadPool {
public static void main(String[] args) {
//使用線程池工廠類裏面的靜態方法newFixedThreadPool生產一個指定數量的線程池
ExecutorService es = Executors.newFixedThreadPool(2);
//調用ExecutorServices中的方法Submit傳遞進程實現類開啓run方法
es.submit(new RunnableImpl());
es.shutdown();
//拋出異常
es.submit(new RunnableImpl());
}
}
棧內存溢出java.lang.StackOverflowError
原因:遞歸方法自己調用自己沒有停止條件
public class Demo01Recursion {
public static void main(String[] args) {
a();
}
private static void a() {
System.out.println("a方法執行了");
a();
}
}
java.io.IOException: Stream closed
public class Demo03CloseAndFlush
{
public static void main(String[] args) throws IOException {
// 1.創建FileWriter對象,構造方法中綁定要寫入數據的目的地
FileWriter fw = new FileWriter("day14_JavaIo\\a.txt");
// 2.使用FIleWriter中的對象Write把數據寫入到內存緩衝區中(字符轉換爲字節的過程)
fw.write(97);
// 3.使用FileWriter中的方法flush,把內存緩衝區中的數據刷新到文件中
fw.flush();
fw.write(98);
// close方法之後流已經關閉了,已經從內存中消失了,流就不能再使用了
fw.close();
fw.write("測試");
}
}