首页 > 解决方案 > 异常处理执行流程

问题描述

我有以下代码。

当客户不存在时,它执行 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.");
    }
}

标签: javaexception

解决方案


您可以执行以下操作:

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.");
        }
    }

推荐阅读