05_java异常机制

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);
	}
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值