异常机制复习笔记
软件在运行过程中,非常可能遇到刚刚提到的问题,我们称之为异常,英文为exception,意思是例外。
本质
当程序出现错误,程序安全退出的机制
处理过程
Java是采用面向对象的方式来处理异常的。
- 抛出异常:在执行一个方法时,如果发生异常,则这个方法生成代表该异常的一个对象,停止当前执行路径,并把异常对象提交给JRE(Java运行时的环境)
- 捕获异常:JRE得到该异常后,寻找相应的代码来处理该异常。JRE在方法的调用栈中查找,从生成异常的方法开始回溯,知道找到相应的异常处理为止。
e.g.
public class test {
public static void main(String[] args) {
int a = 1 / 0;//0不能做除数
System.out.println(a);
}
}
Error
表明JVM已经处于不可恢复的崩溃状态,我们不需要管它,重启即可。
常见异常分类
RuntimeException 运行时异常
运行时异常,需要程序员处理
空指针异常
public class test {
public static void main(String[] args) {
String str = null;
str.length();
}
}
解决空指针异常:增加非空的判断即可。
类型转化异常
public class test {
public static void main(String[] args) {
Animal a = new Dog();
Cat c = (Cat) a;
}
}
class Animal{
}
class Dog extends Animal{
}
class Cat extends Animal{
}
数组越界异常
public class test {
public static void main(String[] args) {
int []arr = new int[5];
System.out.println(arr[5]);
}
}
NumberFormatException(数字格式化) 异常
public class test {
public static void main(String[] args) {
String str ="1234abcd";
System.out.println(Integer.parseInt(str));
}
}
CheckedException 已检查异常
使用try-catch捕获或使用throw抛出
try-catch-finally捕获异常
多个catch子类在前,父类在后
public class test {
public static void main(String[] args) {
FileReader reader = null;
try {
reader = new FileReader("d:/a.txt");
char c =(char) reader.read();
System.out.println(c);
char c2 =(char) reader.read();
System.out.println(""+c+c2);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (reader!=null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
throw抛出异常
public class Test {
public static void main(String[] args) throws IOException {
FileReader reader = null;
reader = new FileReader("d:/a.txt");
char c =(char) reader.read();
System.out.println(c);
char c2 =(char) reader.read();
System.out.println(""+c+c2);
if (reader!=null){
reader.close();
}
}
}
自定义异常
public class Test {
public static void main(String[] args) {
Person person = new Person();
person.setAge(-10);
}
}
class Person{
private int age;
public void setAge(int age) {
if (age<0){
throw new IllegalException("年龄不能为负数");
}
this.age = age;
}
}
class IllegalException extends RuntimeException{
public IllegalException(){
}
public IllegalException(String msg){
super(msg);
}
}
//自定义异常继承RuntimeException
public class Test {
public static void main(String[] args) {
Person person = new Person();
person.setAge(-10);
}
}
class Person{
private int age;
public void setAge(int age) {
if (age<0){
try {
throw new IllegalException("年龄不能为负数");
} catch (IllegalException e) {
e.printStackTrace();
}
}
this.age = age;
}
}
class IllegalException extends Exception{
public IllegalException(){
}
public IllegalException(String msg){
super(msg);
}
}
//自定义异常继承Exception