繁体   English   中英

异常处理执行流程

[英]Exception handling execution flow

我有以下代码。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM