博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Checked Exception & Unchecked Exception
阅读量:7033 次
发布时间:2019-06-28

本文共 2406 字,大约阅读时间需要 8 分钟。

查Spring事务管理时看到一句话:

Spring使用声明式事务处理,默认情况下,如果被注解的数据库操作方法中发生了unchecked异常,所有的数据库操作将rollback;如果发生的异常是checked异常,默认情况下数据库操作还是会提交的。

 

那么,什么是Checked Exception & Unchecked Exception ?

Unchecked Exception:a. 指的是程序的瑕疵或逻辑错误,并且在运行时无法恢复。b. 包括Error与RuntimeException及其子类,如:OutOfMemoryError, UndeclaredThrowableException, IllegalArgumentException, IllegalMonitorStateException, NullPointerException, IllegalStateException, IndexOutOfBoundsException等。c. 语法上不需要声明抛出异常。Checked Exception:a. 代表程序不能直接控制的无效外界情况(如用户输入,数据库问题,网络异常,文件丢失等)b. 除了Error和RuntimeException及其子类之外,如:ClassNotFoundException, NamingException, ServletException, SQLException, IOException等。c. 需要try catch处理或throws声明抛出异常。

但是,为毛"Spring使用声明式事务处理,默认情况下,如果被注解的数据库操作方法中发生了unchecked异常,所有的数据库操作将rollback;如果发生的异常是checked异常,默认情况下数据库操作还是会提交的。"?

另外,@Transactional()

org.springframework.transaction.support.TransactionTemplate

@Override    public 
T execute(TransactionCallback
action) throws TransactionException { if (this.transactionManager instanceof CallbackPreferringPlatformTransactionManager) { return ((CallbackPreferringPlatformTransactionManager) this.transactionManager).execute(this, action); } else { TransactionStatus status = this.transactionManager.getTransaction(this); T result; try { result = action.doInTransaction(status); } catch (RuntimeException ex) { // Transactional code threw application exception -> rollback rollbackOnException(status, ex); throw ex; } catch (Error err) { // Transactional code threw error -> rollback rollbackOnException(status, err); throw err; } catch (Exception ex) { // Transactional code threw unexpected exception -> rollback rollbackOnException(status, ex); throw new UndeclaredThrowableException(ex, "TransactionCallback threw undeclared checked exception"); } this.transactionManager.commit(status); return result; } }

 

如何改变默认规则:

  1, 让checked exception也回滚: @Transactional(rollbackFor=Exception.class)
  2, 让unchecked exception不回滚: @Transactional(notRollbackFor=RunTimeException.class)
  3, 不需要事务管理的(只查询的)方法: @Transactional(propagation=Propagation.NOT_SUPPORTED)

 

转载地址:http://ipyal.baihongyu.com/

你可能感兴趣的文章
android 自定义系统键盘
查看>>
MySQL 查询优化器(总结)
查看>>
2014年6月28日
查看>>
android读取手机验证码
查看>>
何时进行重构?
查看>>
centos6.2x64系统配置本地yum源
查看>>
Java Strategy 模式简介
查看>>
CDH-cdh5.8.3离线安装--Mysql5.7二进制部署
查看>>
flask request 对象
查看>>
【VMware虚拟化解决方案】Horizon-View GPU虚拟化
查看>>
Redis 对象
查看>>
Android应用程序获取ROOT权限的方法
查看>>
KVM主机在线增加硬盘爬坑记
查看>>
【Linxu学习004】Bash Shell 相关
查看>>
Linux 下的shell
查看>>
iptables 知识-filter表
查看>>
Windows平台视频显示问题
查看>>
python性能分析
查看>>
备份与还原---bacula简介
查看>>
Windows Live Writer Test
查看>>