一、概述:Java的异常体系
java中Throwable是异常体系的超类,直接来源于Object类,Throwable可以分为Error类和Exception类,分别表示错误和异常
1、Error类是程序无法处理的错误,由jvm产生和抛出,遇到错误,jvm一般会选择终止线程
2、Exception类分为RuntimeException(运行时异常)和非运行时异常
RuntimeException:例如空指针异常,数组越界异常等,开发时应避免此类异常。也称为非受检异常。
非运行时异常:就是Exception类中除运行类异常之外的异常,如果不处理这类异常,程序都无法编译通过,例如io异常和sql异常。

try,catch语句
如果没有try、catch包裹,代码就不会执行打印语句,如果有try语句,那么捕获异常后就会打印出来,不会影响后续代码的执行
public static void main(String[] args) {
        int[] a = new int[5];
        for (int i = 0; i <10; i++) {
            a[i] = i;
        }
//        try {
//            for (int i = 0; i <10; i++) {
//                a[i] = i;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
       System.out.println("----------------");
    } 
 
1、throws抛出异常
如果定义了一个B方法,然后通过throws抛出异常,当B方法产生了异常,throws就会向上抛出这个异常,比如A方法调用了B方法,B方法抛出的异常就需要A来捕获处理。
public static void main(String[] args) {
		
		Test test = new Test();
		try {
			test.run();
		} catch (CloneNotSupportedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println("--------------");
		
	}
	
	public void run() throws CloneNotSupportedException {
		this.sun();
	}
	
	public void sun() throws CloneNotSupportedException {
		User user01 = new User();
		User user02 = user01.clone();
		System.out.println(user01);
		System.out.println(user02);
		user01.ChangedPerson("李四");
		System.out.println(user01.getPerson());
		System.out.println(user02.getPerson());
	} 
 
2、throw抛出异常
我们可以在方法内,手动抛出一个异常,在上层捕获,写在方法的内部,抛出异常后,后面的代码不会执行,然后就是进行异常的处理。在catch语句中处理。同样也可以在catch语句中向上层抛出一个异常。
Try{
//可能会发生异常的代码
}catch(Exceptione){
      throw newException(e);
} 
 
异常处理的步骤:
try语句中是可能会产生异常的代码,catch语句中如果产生了这个异常,执行对应的操作语句,finally语句,就是一定会执行的代码。

try catch语句使用的方式
1、try,catch,finally均不能单独使用,try···catch // try···catch ···finally
2、try,catch,finally中变量的作用域均是内部的代码块,如果在这三个块中访问,则需要将变量定义在外部。
3、多个catch块时最多只会匹配一个catch块,其余不会执行
4、先catch子类异常,再catch父类的异常
try、catch捕获示意图:













