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("测试");
}
}