【Java】深入理解异常处理机制

2021/6/14 1:23:43

本文主要是介绍【Java】深入理解异常处理机制,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.异常概述

1.1 什么是异常

     异常指程序运行过程中,出现的意外情况,这些意外会导致程序出错或者崩溃,从而影响程序的正常执行

1.2 异常体系

 java.lang.Throwable
     |-----java.lang.Error:一般不编写针对性的代码进行处理。
     |-----java.lang.Exception:可以进行异常的处理
        |------编译时异常(checked)
             |-----IOException
                 |-----FileNotFoundException
             |-----ClassNotFoundException
        |------运行时异常(unchecked,RuntimeException)
             |-----NullPointerException 空指针异常
             |-----ArrayIndexOutOfBoundsException 数组下标越界异常
             |-----ClassCastException 类型转换异常
             |-----NumberFormatException 数字格式异常
             |-----InputMismatchException 输入不匹配异常
             |-----ArithmeticException 算术异常

1.2 运行时异常和编译时异常

     运行时异常是指编译器不要求强制处置的异常。一般是指编程时的逻辑错误,是程序员应该积极避免其出现的异常。

java.lang.RuntimeException类及它的子类都是运行时异常

     编译时异常是指编译器要求必须处置的异常。编译器要求必须捕获或声明所有编译时异常。对于这类异常,如果程

序不处理,可能会带来意想不到的结果

2.异常处理

2.1 throws

throws抛出异常给调用者处理

    public void threadSleep() throws InterruptedException {
        //让线程休眠1秒
        Thread.currentThread().sleep(1000);
    }

2.2 throw

throw抛出一个对象,该对象可分为检查异常和非检查异常

public class Student {
    private int stuAge;
    private String stuName;

    public int getStuAge() {
        return stuAge;
    }

    public void setStuAge(int stuAge) {
        if (stuAge < 0 || stuAge > 120) {
            /**
             * 常见的运行时异常RuntimeException及其子类属于非检查异常,可以不处理
             */
            throw new RuntimeException("不合法的年龄");
        }

        this.stuAge = stuAge;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) throws Exception {
        if (stuName.length() > 20) {
            /**
             * 常见的编译时异常Exception及其子类属于检查异常,必须处理
             */
            throw new Exception("名字长度过长");
        }
        this.stuName = stuName;
    }
}

2.3 try...catch...finally

无论异常是否被捕获,finally的代码一定会被执行

    /**
     * 读取文件,假设文件存在
     *
     * @param filePath
     */
    public void readFile(String filePath) {
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            File file = new File(filePath);
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);

            byte[] bytes = new byte[1024];
            int len;
            while ((len = bis.read(bytes)) != -1) {
                System.out.println(new String(bytes, 0, len));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

3.自定义异常

public class Student {
    private int stuAge;
    private String stuName;

    public int getStuAge() {
        return stuAge;
    }

    public void setStuAge(int stuAge) {
        if (stuAge < 0 || stuAge > 120) {
            /**
             * 常见的运行时异常RuntimeException及其子类属于非检查异常,可以不处理
             */
            throw new AgeIsIllegal("不合法的年龄");
        }

        this.stuAge = stuAge;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) throws NameIsLongException {
        if (stuName.length() > 20) {
            /**
             * 常见的编译时异常Exception及其子类属于检查异常,必须处理
             */
            throw new NameIsLongException("名字长度过长");
        }
        this.stuName = stuName;
    }
}

/**
 * 自定义非检查异常
 */
class AgeIsIllegal extends RuntimeException {
    public AgeIsIllegal(String message) {
        super(message);
    }
}

/**
 * 自定义检查异常
 */
class NameIsLongException extends Exception {
    public NameIsLongException(String message) {
        super(message);
    }
}

 



这篇关于【Java】深入理解异常处理机制的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程