java - 异常处理执行流程
问题描述
我有以下代码。
当客户不存在时,它执行 Throw Number 1。
执行继续并到达 Throw Number 2。
所以显示的消息最终是来自 Throw Number 2 的消息。
但我不希望这种情况发生。
当执行到达 Throw Number 1 时,它应该停在那里并且永远不会到达 Throw Number 2,以便显示来自 Throw Number 1 的消息。
怎么做?
public void updateCustomerName(int customerId, String name){
try {
//code to find customer by id here
if(customerExists.isEmpty() == false) {
//code to update customer name here
}
else {
//THROW NUMBER 1
throw new CustomerAPICustomException("Invalid customer id : " + customerId);
}
}
catch(Exception ex) {
//THROW NUMBER 2
throw new CustomerAPICustomException("Customer update error.");
}
}
解决方案
您可以执行以下操作:
public void updateCustomerName(int customerId, String name){
if(customerExists.isEmpty()) {
throw new CustomerAPICustomException("Invalid customer id : " + customerId);
}
try{
//customer update
}
catch(Exception ex) {
//THROW NUMBER 2
throw new CustomerAPICustomException("Customer update error.");
}
}
推荐阅读
- python - 如果指定列不为空,则重复列元素
- asp.net - IdentityServer 4 中的 CORS 问题
- php - Laravel:如何从城市名称中获取纬度和经度点?
- scala - 使用scala获取kafka主题名称
- python - 关闭 QMainWindow 的正确方法
- c - 在这一行需要解释(树,递归)
- angular - Starting out with SASS, SCSS and Bootstrap in Angular project
- javascript - 将 Array.prototype.includes 与 Typescript 一起使用时,Jest 测试失败?
- node.js - Redis 简单消息队列(RSMQ)和公牛队列有什么区别?
- c# - 比较一个属性上的两个列表,不要添加重复项