1 异常的基本概念
异常机制的本质:当程序出现错误,程序安全退出的机制。
1.1 java处理异常的方式:
- 抛出异常:执行方法发生异常,将这个方法封装成一个对象,停止当前执行,并把异常对象提交给JRE。
- 捕获异常:JRE得到该异常后,寻找相应的代码来处理该异常。
1.2 错误和异常的分类:
- Error:表明JVM已经处于不可恢复的崩溃状态中。
- Exception:指程序本身能够处理的异常,分为RuntimeException(运行时异常)和CheckedException(已检查异常)。
2 常见的异常
2.1 RuntimeException:
RuntimeException类异常在编译时不会报错,运行时才会报错。
- ArithmeticException(算数异常)
System.out.println(1/0);
- ArrayIndexOutOfBoundsException(数组下标越界异常)
String[] a = new String[5];
System.out.println(a[5]);
- NullPointerException(空指向异常)
String str = null;
str.length();
- ClassCastException(类型转换异常)
public class TestRuntimeException {
public static void main(String[] args) {
Animal a = new Dog();
Cat c = (Cat) a;
}
}
class Animal {
}
class Dog extends Animal {
}
class Cat extends Animal {
}
- NumberFormatException(数字格式异常)
String str = "123abdf";
System.out.println(Integer.parseInt(str));
2.2 CheckedException
CheckedException异常属于检查型异常,在编译时就会报错,必须进行异常处理。
捕获异常:try…catch…finally
public class TestCheckedException {
public static void main(String[] args) {
FileReader file = null;
try {
file = new FileReader("F:\\project\\cc.txt");
file.read();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.println("不管是否发生异常,都会执行");
}
}
}
抛出异常:throws
public class TestCheckedException2 {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("F:\\project\\cc.txt");
file.read();
}
}
自定义异常(手动抛出):throw
public class TestThrows {
public static void main(String[] args) {
Person p = new Person();
p.setAge(-100);
}
}
class Person {
int age;
public void setAge(int age) {
if(age < 0) {
throw new illAgeException("年龄不能为负数");
}
this.age = age;
}
}
class illAgeException extends RuntimeException {
public illAgeException(String msg) {
super(msg);
}
}