首页 > 其他 > 详细

74 throw 和 throws 的区别?

时间:2020-06-03 21:37:11      阅读:87      评论:0      收藏:0      [点我收藏+]

throw 和 throws 的区别?

答:

throw:

  1. 表示方法内抛出某种异常对象

  2. 如果异常对象是非 RuntimeException 则需要在方法申明时加上该异常的抛出 即需要加上 throws 语句 或者 在方法体内 try catch 处理该异常,否则编译报错

  3. 执行到 throw 语句则后面的语句块不再执行
    ?

throws:

  1. 方法的定义上使用 throws 表示这个方法可能抛出某种异常

  2. 需要由方法的调用者进行异常处理
    ?

原文链接: https://www.baidu.com/link?url=89GNoFcJCTAuw3HiyVe0huX7hhbWBUpC_SnuxGmqUGibYN3rBm8sbWca9L502qco632sPXuqiGmfXX4jK-fjy5kVfIrfVpGdfe1Qt-sjS9K&wd=&eqid=f2df13c30001097c000000065ed79a83 (理解)
原文链接: https://www.baidu.com/link?url=rQoA1N3TZFWW-9BJY3u0ImYvzieFLxXMdtxUDT6-LhYBMNAO37BLrFPcdJb4HnJ11F9nazXVd3rr1K3aoMrIOq&wd=&eqid=f2df13c30001097c000000065ed79a83 (概念,代码)
?

package constxiong.interview;
 
import java.io.IOException;
 
public class TestThrowsThrow {
 
	public static void main(String[] args) {
		testThrows();
		
		Integer i = null;
		testThrow(i);
		
		String filePath = null;
		try {
			testThrow(filePath);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 测试 throws 关键字
	 * @throws NullPointerException
	 */
	public static void testThrows() throws NullPointerException {
		Integer i = null;
		System.out.println(i + 1);
	}
	
	/**
	 * 测试 throw 关键字抛出 运行时异常
	 * @param i
	 */
	public static void testThrow(Integer i) {
		if (i == null) {
			throw new NullPointerException();//运行时异常不需要在方法上申明
		}
	}
	
	/**
	 * 测试 throw 关键字抛出 非运行时异常,需要方法体需要加 throws 异常抛出申明
	 * @param i
	 */
	public static void testThrow(String filePath) throws IOException {
		if (filePath == null) {
			throw new IOException();//运行时异常不需要在方法上申明
		}
	}
}

?

总结:throws可以单独使用,throw不可以,必须搭配try catch,或者throws,若程序执行到throw exception 语句,则后面的语句不会再执行。

?

74 throw 和 throws 的区别?

原文:https://www.cnblogs.com/ynzj123/p/13040062.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!