java

java中的thorw和throws

2020-12-28  本文已影响0人  HachiLin

1. throws关键字

  throws关键字通常应用在声明方法时,用来指定可能抛出的异常。多个异常可以使用逗号隔开。当在主函数中调用该方法时,如果发生异常,就会将异常抛给指定异常对象。

public class ThrowsTest {
    //定义方法并抛出NegativeArraySizeException异常
    public static void testThrows() throws NegativeArraySizeException {
        int[] arr = new int[-3]; //创建不合法数组
    }

    public static void main(String[] args) {
        try {
            testThrows(); //调用testThrows()方法
        } catch (NegativeArraySizeException e) {
            System.out.println("捕捉到throws抛出的异常!");
        }
    }
}

输出:捕捉到throws抛出的异常!

2. throw关键字

  throw关键字通常用在方法体中,并且抛出一个异常对象。程序在执行到throw语句时立即停止,它后面的语句都不执行。通过throw抛出异常后,如果想在上一级代码中来捕获并处理异常,则需要在抛出异常的方法中使用throws关键字在方法声明中指明要抛出的异常;如果要捕捉throw抛出的异常,则必须使用try—catch语句。

public class ThrowTest {
    private static class MyException extends Exception {
        String message;
        public MyException(String message) {
            this.message = message;
        }

        public String getMessage() {
            return message;
        }
    }

    public static void testThrow() throws NegativeArraySizeException {
        try {
            throw new MyException("这是我自定义的异常!");
        } catch (MyException e) {
            System.out.println("捕捉到throw抛出的异常:" + e.getMessage());
        } finally {
            int[] arr = new int[-3];  // 将异常返回给上一级方法
        }
    }

    public static void main(String[] args) {
        try {
            testThrow();
        } catch (NegativeArraySizeException e) {
            System.out.println("捕捉到throws抛出的异常!");
        }
    }
}

输出:

捕捉到throw抛出的异常:这是我自定义的异常!
捕捉到throws抛出的异常!
上一篇 下一篇

猜你喜欢

热点阅读