异常

异常及其处理

初识异常

很多事件并非总是按照人们自己设计意愿顺利发展的,经常出现这样那样的异常情况。例如: 你计划周末郊游,计划从家里出发→到达目的→游泳→烧烤→回家。但天有不测风云,当你准备烧烤时候突然天降大雨,只能终止郊游提前回家。“天降大雨”是一种异常情况,你的计划应该考虑到这样的情况,并且应该有处理这种异常的预案。
Java 中的异常又称为例外,是一个在程序执行期间发生的事件,它中断正在执行程序的正常指令流。为了能够及时有效地处理程序中的运行错误,必须使用异常类,这可以让程序具有极好的容错性且更加健壮。

在 Java 中一个异常的产生,主要有如下三种原因:
1. Java 内部错误发生异常,Java 虚拟机产生的异常。
2. 编写的程序代码中的错误所产生的异常,例如空指针异常、数组越界异常等。
3. 通过 throw 语句手动生成的异常,一般用来告知该方法的调用者一些必要信息。

运行时异常都是 RuntimeException 类及其子类异常,如 NullPointerException、IndexOutOfBoundsException 等,这些异常是不检查异常,程序中可以选择捕获处理,也可以不处理。这些异常一般由程序逻辑错误引起,程序应该从逻辑角度尽可能避免这类异常的发生。

非运行时异常是指 RuntimeException 以外的异常,类型上都属于 Exception 类及其子类。从程序语法角度讲是必须进行处理的异常,如果不处理,程序就不能编译通过。如 IOException、ClassNotFoundException 等以及用户自定义的 Exception 异常(一般情况下不自定义检查异常)。
image

public class Text0 {
    public static void main(String[] args) {
        System.out.println("start");
        method();
        System.out.println("end");
    }

    public static void method(){
            int [] arr = {1,2,3} ;
            System.out.println(arr[3]);
        }
	//编译结果为"start"并抛出了ArrayIndexOutOfBoundsException

异常处理

现在改进上面的代码,用try-catch解决。
包括了一些常用方法

public class Text0 {
    public static void main(String[] args) {
        System.out.println("start");
        method();
        System.out.println("end");
    }

    public static void method(){
        try {
            int [] arr = {1,2,3} ;
            System.out.println(arr[3]);//new ArrayIndexOutOfBoundsException("xxx")
        } catch (ArrayIndexOutOfBoundsException e) {//e 变成了一个对象

            //public String getMessage();返回此 throwable 的详细消息字符串
//            System.out.println(e.getMessage());//Array index is out of bounds

            //public String toString ():返回此可抛出的简短描述
//            System.out.println(e.toString());//java.lang.ArrayIndexOutOfBoundsException: 3

            //public void printStackTrace();把异常的错误信息输出在控制台
            //e.printStackTrace();
        }
    }
}
/*运行结果为 start
             end
*/

**用throw或者throws解决
这次换个实例来说明

public class Text2 {
    public static void main(String[] args) {
        try {
            new Text2().text(1,0);
        } catch (Exception e) {
            System.out.println("b不能为0");

        }//用了try catch 捕获异常,使得程序可以继续往下执行
        System.out.println("Hello,World!");
    }
    //假设这个方法中,处理不了这个异常。方法上抛出异常
    public void text(int a,int b) throws   ArithmeticException{
//        if(b==0){
//            throw new ArithmeticException();//主动抛出异常,一般在方法中使用
//        }
        System.out.println(a/b);
    }//实际上这是运行类异常,它自己就会抛出
}

接下来是异常的一些另外须知:
同时检测多个异常时,把检测范围大的放在后面

public class Text {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        //ctrl + alt + t
        //假设捕获多个异常
        try {//try 监控区域
            System.out.println(a/b);
        } catch (Exception e) {//catch 捕获异常
            System.out.println("b不能为0");
        e.printStackTrace();
        }catch (Error error){
            System.out.println("Error");
        }catch (Throwable throwable){
            System.out.println("Throwable");
        }//同时检测多个异常时,把检测范围大的放在后面
        finally {//处理善后工作,总是会执行
            System.out.println("finally");
        }
        System.out.println("end");
        //finally 可以不要finally       假设IO,资源,关闭!能用到;

    }
}
posted @ 2022-05-11 09:03  HFUUwzy  阅读(43)  评论(0编辑  收藏  举报