JavaSE常见的异常总结
在写代码的时候不可能不出现问题,遇到问题能够第一时间解决问题是每一个开发人员必备的技能。
解决这些问题,就需要靠我们平时的积累。你遇到的问题多了,并且善于总结,以后遇到同样的问题就不在话下了。
ArrayIndexOutofBoundsException
数组索引越界异常 数组索引超过索引最大值或最小值,就会出现这个异常。
int[] arr={1,2,3,4,5};
for(int i=1;i<=arr.lengthi++){
System.out.println(arr[i]);
}
StringIndexOutofBoundsException
字符串索引越界异常 字符串索引超过索引最大值或最小值,就会出现这个异常。
一般在调用字符串方法时,传递索引参数非法报错。如下调用subtring()方法
String str="helloworld";
String result=str.substring(0,15);
IndexOutofBoundsException
索引越界异常 一般对调用List方法传递非法索引时,出现此异常。
ArrayList<String> list=new ArrayList<>();
list.get(10);
NullPointerException 空指针异常
遇到下面几种情况都会出现空指针异常
a:当数组为null时,去访问数组的元素
b: 当对象为null时,去调用对象的方法或属性
String str=null;
String[] arr=str.split(",");
IllegalArgumentException 非法的参数异常
一般在调用API方法时传递一个非法的数据,出现此异常
Random r=new Random();
//随机生成一个0~0又不包括0的整数,这样的数根本就不存在。
int num=r.nextInt(0);
NoShchElementException 没有找到元素
迭代器在遍历集合时,没有元素可以迭代出现此异常
ArrayList<String> list=new ArrayList<>();
list.add("hello");
list.add("world");
//高级for底层是迭代器实现的
Iterator it=list.iterator();
while(it.hashNext()){
System.out.println(it.next());
}
//上面选好结束已经没有元素了,再调用next()就会出现此异常
System.out.println(it.next());
FileNotFoundException
文件没有找到异常,当文件路径不正确的时候出现此异常
C://abc目录根本流不存在,创建对象失败
FileOutputStream fos=new FileOutputStream("C:\\abc\\a.txt");
FileNotFoundException: day01-code (拒绝访问。)
IO流关联的是一个文件夹路径不能操作,IO流要对文件进行读和写的操作
C:\\abc是一个文件夹路径,流只能操作文件
FileOutputStream fos=new FileOutputStream("C:\\abc");
ConcurrentModificationException
并发修改异常,当使用迭代器或者高级for遍历集合时,集合自己去增删集合中的元素,就会出现此异常。
List<String> list=new ArrayList<>();
list.add("hello");
list.add("java");
list.add("php");
//高级for在遍历集合的时候,集合自己不能添加元素
for(String s:list){
if(s.equals("hello")){
list.add("android");
}
}
ClassCastException
类型转换异常, 多态时候,把父类型变为子类型。转换错误就出现此异常
Object obj=new ArrayList();
//数据类型转报错,因为obj原本表示ArrayList对象,不是HashSet对象。
HashSet set=(HashSet)obj;
ParseException 解析异常
在基础阶段就是日期解析时,字符串和SimpleDateFormat的格式不匹配
Date date=new Date(time);
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
//日期格式不匹配
String time = sdf.parse("2018/08/08");
UnsupportedOperationException
不支持的操作异常
//List的of(...)方法得到的是一个不可变的集合,不支持增加删除改操作
List<Integer> list=List.of(1,2,3,4,5);
list.add(6);//报错
IOException: Stream Closed
流被关闭了,就不能读和写了
FileOutputStream fos=new FileOutputStream("C:\\abc\\a.txt");
fos.write("hello".getBytes());
fos.close();
//流已经完毕,不能再进行写入操作
fos.write("world".getBytes());
java.lang.ArithmeticException: / by zero
算术异常,除数不能为0
int a=10;
//除数不能为0
int b=a/0;
java.lang.NumberFormatException
数据格式异常,一般在做数据转换的时候数据不符合格式出现此异常。
//Integer不能把非整数的字符串,包装成Integer对象
Integer in1 = Integer.valueOf("1a");
System.out.println(in1);
NotSeriableException
没有序列化异常,一个类必须实现Seriiable接口才能被序列化,否则就会出现此异常
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("a.txt"));
//把Student对象写入到a.txt文件中,必须让Student实现Seriable接口才能完成此操作。
oos.wirte(new Student("张三",20));
oos.close();