throws和throw的区别

mac2024-05-28  53

throws用在方法声明上,抛出了异常性,但是异常不一定会发生; throw用在方法内部,抛出即表明一定发生了异常;

根据try…catch…也可以模拟JVM抛出异常

public class MyTest { public static void main(String[] args) throws ArithmeticException,NullPointerException{ Scanner scanner = new Scanner(System.in); System.out.println("请输入第一个整数"); int a = scanner.nextInt(); System.out.println("请输入第二个整数"); int b = scanner.nextInt(); double r = test(a, b); System.out.println(r); System.out.println("abc"); } private static double test(int a, int b) { if (b == 0) { throw new ArithmeticException("除数为0"); } else { return a / b; } } }
最新回复(0)