throws与throw

1.throws关键字–>作用于方法上

在进行方法定义时,如果要明确告诉调用者方法可能产生哪些异常,可以使用throws方法进行声明,表示将异常抛回给调用方,并且当方法出现问题后,可以不进行处理。

public class Test {

	public static void main(String[] args) {
		try {
			System.out.println(calculate(10, 0));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static int calculate(int x,int y)throws Exception {//抛给调用者
		return x/y;
	}
}
/*
 * java.lang.ArithmeticException: / by zero
 *	at Test.Test.calculate(Test.java:13)
 *  at Test.Test.main(Test.java:7)
 */

2.throw关键字–>作用于方法中,主要表示手工异常抛出

public class Test {

	public static void main(String[] args) {
		try {
			throw new Exception("抛异常");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_40995778/article/details/83585685
今日推荐