我是靠谱客的博主 慈祥滑板,这篇文章主要介绍Java面试题 (2) Java中 throw 和 throws 的区别?,现在分享给大家,希望可以做个参考。

Java面试题 :throw 和 throws 的区别 ?

Java 中抛出异常有3种方式,分别是 throw throws 系统自动抛出。

系统自动抛出:

当开发人员自己编写代码出现异常(主义错误,逻辑错误,转义错误),该异常如果自己没捕捉,则系统会自动抛出 。系统会把异常所在的位置,异常的名称,异常的原因 等 信息打印在 控制台中,并终止程序往下执行。


throw :

throw是语句中抛出异常,一般都是在代码块中,当程序中某种逻辑错误时由开发人员主动抛出自己指定类型异常。创建的是一个异常对象,确定某种异常才能使用,定义在方法体内,必须搭配 thy / catch 或者 throws 一起使用。

栗子:

搭配 thy / catch 使用

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
try{ int effectedNum = productCategoryDao.batchInsertProductCategory(productCategoryList); if (effectedNum <=0){ throw new ProductCategoryOperationException("店铺类别创建失败"); }else { return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS); } }catch (Exception e){ hrow new ProductCategoryOperationException("batchInsertProductCategory error"+e.getMessage()); }

搭配 throws 使用

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public ProductCategoryExecution deleteProductCategory(long productCategoryId, long shopId) throws ProductCategoryOperationException { try{ int effectedNum = productDao.updateProductCategoryToNull(productCategoryId); if (effectedNum < 0){ throw new RuntimeException("商品类别更新失败"); } }catch (Exception e){ throw new RuntimeException("deleteProductCategory error:"+e.getMessage()); } //将此商品类别下的商品的类别id置空 try{ int effectedNum = productCategoryDao.deleteProductCategory(productCategoryId,shopId); if (effectedNum <=0){ throw new ProductCategoryOperationException("商品类别删除失败"); }else { return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS); } }catch (Exception e){ throw new ProductCategoryOperationException("deleteProductCategory error:"+e.getMessage()); } }

throws :

在方法参数后(方法头的位置),throws 可以 跟着 多个异常名,多个抛出的异常用逗号隔开。
表示在调用该方法的类中抛出异常(可以理解往上抛),不在该类中解决,预计这个方法可能出现的异常。

栗子:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public ProductCategoryExecution batchInsertProductCategory(List<ProductCategory> productCategoryList) throws ProductCategoryOperationException,RuntimeException { if (productCategoryList!=null && productCategoryList.size()>0){ try{ int effectedNum = productCategoryDao.batchInsertProductCategory(productCategoryList); if (effectedNum <=0){ throw new ProductCategoryOperationException("店铺类别创建失败"); }else { return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS); } }catch (Exception e){ throw new ProductCategoryOperationException("batchInsertProductCategory error"+e.getMessage()); } }else { return new ProductCategoryExecution(ProductCategoryStateEnum.EMPTY_LIST); } }

附:

1)throws 用在方法声明后,跟在后面的是异常类名 (Execution ),throw 用在方法体内,跟的是异常的对象名 (new Execution)。
2)throws 后可以跟多个异常类名,用逗号隔开;而 throw 只能抛出一个异常对象名。
3)throws 表示抛出的异常由该方法调用者处理,throw表示抛出的异常由自己处理(定义方法体内)
4)throws 表示会出现异常的一种可能性,不一定会发生该异常;throw 要是执行了则一定抛出了某种异常且后面的代码都不执行。

最后

以上就是慈祥滑板最近收集整理的关于Java面试题 (2) Java中 throw 和 throws 的区别?的全部内容,更多相关Java面试题内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(87)

评论列表共有 0 条评论

立即
投稿
返回
顶部