I have the following code.
When customer does not exist it executes Throw Number 1.
Execution continues and gets to Throw Number 2.
So the displayed message ends up being the one from 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.
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."); } }
Advertisement
Answer
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."); } }