java 异常

86 阅读2分钟

异常

异常是程序中的一些错误,但并不是所有的错误都是异常,并且错误有时候是可以避免的。
检查性异常、运行时异常、错误
Java将各种常见的异常信息封装成一个类Exception,问题出现的时候,就会创建异常的类对象并抛出相关的信息。

//算术异常  java.lang.ArithmeticException
int a = 1/0;
System.out.println(a);

//空指针异常     java.lang.NullPointerException
String str = null;
System.out.println(str.substring(0,1));

//类型强制转换异常      java.lang.ClassCastException
Class o = (Class)new Object();
System.out.println(o);

//数组下标越界        java.lang.ArrayIndexOutOfBoundsException
int[] arry = new int[2];
System.out.println(arry[2]);

异常的体系

image.png

image.png

总体上我们根据Javac对异常的处理要求,将异常分为2类:
非检查异常:Error和RuntimeException以及他们的子类
检查异常:除了Error和RuntimeException的其他异常

自行处理

image.png

捕获异常

dea快捷键:选中想被try/catch包围的语句,同时按下ctrl+alt+t,

try {
    String str = null;
    str.substring(0,1);
} catch (NullPointerException e) {
    e.printStackTrace();
    System.out.println("空指针异常");
} catch (ArrayIndexOutOfBoundsException e) {
    e.printStackTrace();
    System.out.println("数组下标越界异常");
} catch (Exception e) {
   e.printStackTrace();
}

//程序中有多个语句可能发生异常,可以都放在try语句中,并匹配多个catch语句处理。
//如果异常被catch匹配上,接着执行tr{}catch{}后的语句,没有匹配上程序正常执行
//try中多个异常同时出现,只会处理第一条出现异常的语句,剩下的异常不再处理。

抛出处理

当前方法不知道如何处理、或者不想处理,可以通过throws关键字向调用者抛出一个异常。
调用者可以通过try catch 来处理异常,也可以继续向调用者抛出异常,如果是main方法抛出异常,则交给jvm处理异常。

//抛出处理:不处理或者交给下一个使用者去处理,一般是用于抛出检查性异常
public void add() throws FileNotFoundException {
    System.out.println("c");
    InputStream s = new FileInputStream("dfd");
}

public static void main(String[] args) {
    C a = new C();
    try {
        a.add();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    System.out.println("A");

}

自定义异常

1、定义一个类,并且继承Exception 2、在业务的处理错误的时候,形成一个异常 throw关键字: 语句抛出异常 htrows关键字: 声明异常(方法抛出一个异常)

public class D {
    public static void main(String[] args) throws LunGenException {
        String str = "haodfjhiod";
        if (str.equals( "haodfjhiod")){
            throw new LunGenException();
        }

    }
}
//    1、定义一个类,并且继承Exception
//    2、在业务的处理错误的时候,形成一个异常
class  LunGenException extends Exception {
    public  LunGenException(){
//        System.out.println("我抛出了异常");
    }
}

finally

在try catch 只能跟一个finally
无论try里面有没有发生,都会执行finally语句。
在finally代码块中,可以运行清理类型等收尾善后性质的语句

//finally 只要程序进入了try的范围,那么使用return会先执行,但是在输出结果之前,会执行finally.
public static void main(String[] args) {
    E a = new E();
    System.out.println(a.a());
}
public  int a (){
    try {
        System.out.println("A");
        int i = 10/0;
        System.out.println("B");
        return 20;
    } catch (Exception e) {
        System.out.println("抛出算术异常");
    } finally {
        System.out.println("finally执行");
    }
    return 30;
}