欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

3.throws throw try-catch-finally 自定义异常类

程序员文章站 2022-03-07 22:37:19
...
import java.io.*;

public class ExceptionTest {
    /**
     * 参考:https://blog.csdn.net/qq_29229567/article/details/80773970
     * Error(错误) VS Exception(异常)
     * Exception分为:运行时异常(RuntimeException) VS 非运行时异常(非RuntimeException)
     * 可查异常(Exception下非RuntimeException) VS 不可查异常/错误(RuntimeException+Error)
     * Java规定,对于可查异常必须捕捉、或者声明抛出,允许忽略不可查异常/错误
     * NoClassDefFoundError类定义错误(属于Error) VS ClassNotFoundException类找不到异常(属于Exception)
     * throws throw try-catch-finally 如何使用?
     * 如何自定义异常类?
     */

    public static void main(String[] args) {
        ArithmeticExceptionTest(0);
        FileNotFoundExceptionANDIOExceptionTest("E://test.txt");
        try {
            ThrowsTest("E://test.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
        ThrowTest(5);
        SelfDefExceptionTest(5);
    }
    
    // 属于RuntimeException (执行时才会报出异常)
    public static void ArithmeticExceptionTest(int i) {
        System.out.println(10 / i);
    }

    // 非RuntimeException=可查异常(编译器要求必须处置的异常)
    public static void FileNotFoundExceptionANDIOExceptionTest(String filename) {
        try {
            BufferedReader in = new BufferedReader(new FileReader(filename));
            String str;
            while ((str = in.readLine()) != null) {
                System.out.println(str);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // throws在方法上外抛异常,上面处理异常或者再往上面throws异常,main方法可以抛出异常。
    private static void ThrowsTest(String filename) throws IOException {
        BufferedReader in = new BufferedReader(new FileReader(filename));
        String str;
        while ((str = in.readLine()) != null) {
            System.out.println(str);
        }
    }

    // throw(try代码块中自定义抛出什么异常)
    private static void ThrowTest(int a) {
        try {
            if (10 > a) {
                throw new Exception("对不起,您输入的值不能小于10!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("finally 除开一些特例一定都会执行的!\n" +
                    "     1)在finally语句块中发生了异常。\n" +
                    "     2)在前面的代码中用了System.exit()退出程序。\n" +
                    "     3)程序所在的线程死亡。\n" +
                    "     4)关闭CPU。");
        }

    }

    // 抛出自定义异常,捕获自定义异常类MyException
    private static void SelfDefExceptionTest(int a) {
        try {
            if (10 > a) {
                throw new MyException("对不起,您输入的值不能小于10!");
            }
        } catch (MyException e) {
            e.printStackTrace();
        }
    }
}

// 自定义MyException类
class MyException extends Exception {
    public MyException(String msg) {
        super(msg);
    }
}