在利用java语言设计程序设计时出现异常是常有的事。
首先我们得知道java工具包中自带的异常的分支体系:
Throwable
Error(错误) Exception(异常)
StackOverflowError RuntimeException(运行时)
OutOfMemoryError IOException
这里就列出了一些,具体的的大家可以去JAVA-API文档查看了解:https://www.matools.com/api/java8
java的异常分为两大类:
一类是:检查异常也叫(编译时异常);另一类是:非检查异常(运行时异常)。
检查异常:
除了Error和RuntimeException以外其他的异常,
javac编译的时候 强制要求我们必须为这样的异常做处理(try或throws),也就是我们编写程序时编译器一般爆红线的时候,就是我们java程序出现了检查异常。
因为这样的异常在程序运行过程中极有可能产生问题的,
异常产生后后续的所有执行就停止啦。
并且这类异常一般都出现在I/0流的读写部分和一些底层反射操作时出现,当出现这类异常可以尝试try catch手段来处理或者是直接通过关键字throws抛出异常就可以了。
如下是几种编译时异常:
1.InterruptException
try{
Thread.sleep(5000);
}catch(InterruptException e){
}
2.FileNotFoundException
File file = new File("D://test//test.txt");
try {
FileReader fileReader=new FileReader(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
3.IOException
File file = new File("D://test//test.txt");
try {
FileReader fileReader=new FileReader(file);
fileReader.read();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
4.ClassNotFoundException
try {
Class.forName("java.lang.String");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
剩下的还有很多检查异常,这要开发的时候逐渐去发现了。
非检查异常:
Error和RuntimeException都算作运行时异常,javac编译的时候,不会提示和发现的,
在程序编写时不要求必须做处理,如果我们愿意可以添加处理手段(try throws)。
这种异常一般发生在你的程序编写语法或者流操作不出现情况的问题下,进过javac编译执行的程序出现错误或异常,这就是非检查异常。如下是几种运行时异常:
1.InputMisMatchException 输入不匹配
int value = input.nextInt();// abc
2.NumberFormatException 数字格式化
int value = Integer.parseInt("123.45");
3.NegativeArraySizeException 数组长度负数
int[] array = new int[-2];
4.ArrayIndexOutOfBoundsException 数组索引越界
int[] array = {1,2,3};
array[5];
5.NullPointerException 空指针异常
int[][] array = new int[3][];
array[0][0] =10;
Person p = null;
p.getName();
6.ArithmeticException 数字异常
10/0 整数不允许除以0 Infinity小数除以0会产生无穷
7.ClassCastException 造型异常
Person p = new Teacher();
Student s = (Student)p;
8.StringIndexOutOfBoundsException 字符串越界
String str = "abc";
str.charAt(5);
9.IndexOutOfBoundsException 集合越界
List家族
ArrayList list = new ArrayList();
list.add(); list.add(); list.add();
list.get(5);
10.IllegalArgumentException 非法参数异常
ArrayList list = new ArrayList(-1);
其中StackOverflowError,OutOfMemoryError也是非检查异常。
除了java自带的异常,我们还可以自定义异常(也就是说属于我们自己编写的异常);
其实现步骤:
1.自己描述一个异常的类
2.让我们自己的类继承
如果继承是RuntimeException---->运行时异常(不需要必须添加处理手段)
如果继承是Exception-------------->编译时异常(必须添加处理手段)
3.创建一个当前自定义异常类的对象
通过throw关键字 主动产生异常