异常使用

import java.io.FileNotFoundException;
import java.nio.file.FileAlreadyExistsException;
import java.util.Random;

public class ExceptionUse {
    public static void main(String[] args) throws FileNotFoundException {
        //n1(){}-调用->m1(){处理异常}
        n1();
        //n2(){处理异常}-调用->m2(){抛异常}
        n2();
        //n3(){抛异常}-调用->m3(){抛异常}
        n3();
        //n03(){抛异常}-调用->m3(){抛异常}
        n03(); //n3==n03
    }

    public static String n1() {
        m1();
        return "123";
    }

    public static String n2() {
        try {
            m2();
        } catch (FileAlreadyExistsException e) {
            e.getMessage();
        }
        return "123";
    }

    public static String n3() throws FileNotFoundException {
        try {
            m3();
        } catch (FileNotFoundException e) {
            throw e;
        }
        return "123";
    }

    public static String n03() throws FileNotFoundException {
        m3();
        return "123";
    }

    public static int m1() {
        int m = new Random().nextInt();
        try {
            if (m != 1) {
                throw new FileAlreadyExistsException("文件已存在异常"); //throw new FileAlreadyExistsException("error")表示出现并抛出异常  但new FileAlreadyExistsException("error")不表示抛出异常
            }
        } catch (FileAlreadyExistsException e) {
            //异常向外抛出之前被catch捕获,若想要继续抛出可在catch里throw
            e.getMessage();
        }
        return m;
    }

    public static int m2() throws FileAlreadyExistsException {
        int m = new Random().nextInt();
        if (m != 1) {
            throw new FileAlreadyExistsException("文件已存在异常");
        }
        return m;
    }

    public static int m3() throws FileNotFoundException {
        int m = new Random().nextInt();
        if (m != 1) {
            throw new FileNotFoundException("文件未找到异常");
        }
        return m;
    }
}
posted @ 2023-03-14 22:27  略乏旅人  阅读(16)  评论(0编辑  收藏  举报