简体   繁体   English

异常处理执行流程

[英]Exception handling execution flow

I have the following code.我有以下代码。

When customer does not exist it executes Throw Number 1.当客户不存在时,它执行 Throw Number 1。

Execution continues and gets to Throw Number 2.执行继续并到达 Throw Number 2。

So the displayed message ends up being the one from Throw Number 2.所以显示的消息最终是来自 Throw Number 2 的消息。

But I don't want that to happen.但我不希望这种情况发生。

When execution gets to Throw Number 1, it should stop there and never get to Throw Number 2 so that the message from Throw Number 1 is the one displayed.当执行到达 Throw Number 1 时,它应该停在那里并且永远不会到达 Throw Number 2,以便显示来自 Throw Number 1 的消息。

How to do that?怎么做?

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

You can do something like:您可以执行以下操作:

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