Java - 不中断程序的异常

问题描述 投票:0回答:1

例如我有列表、类和方法:

List<Client> myClient = new ArrayList<>();
public class ClientNotFoundException extends RuntimeException {

    public ClientNotFoundException() {
        super("Client not found!");
    }
}
public class Client {
    String firstName;
    String lastName;
    String cID;
    boolean subscription = false;

    public String getFullName(){
        return this.firstName + " " + this.lastName;
    }
}

我的方法:

public String getClientName(String customerID){
    String nameCustomer = null;

    for( Client myCustomer: myClient ){
        if( myClient.clientID == customerID ){
            nameCustomer = myCustomer.getFullName();
            break;
        }
    }

    return nameCustomer;
}

找不到客户端时如何引发异常。我只需要显示消息而不停止程序。这可能吗?

java exception arraylist
1个回答
0
投票

“...我只需要显示消息而不停止程序。...”

您可以利用 标准错误流。

String getClientName(String customerID) {
    for (Client c : myClient)
        if (c.cID.equals(customerID)) return c.getFullName();
    System.err.printf("'%s' not found%n", customerID);
    return null;
}
© www.soinside.com 2019 - 2024. All rights reserved.