首页 > 解决方案 > 我该如何处理这个自定义异常?

问题描述

我有这段代码,它依赖于一个函数抛出的自定义异常,findID()它抛出一个NoClientFound异常,每当这个提到的函数返回 null 时(客户端不存在)。

IDE 建议我将该异常应用到代码中,但在这段代码中,我需要 ID 为空(唯一 ID)我“无法捕获该异常”,因为如果我捕获它,该函数将未按预期执行。

问题:我该如何管理?

有异常问题的函数

public boolean add(Client c) {
        StringBuilder sb = new StringBuilder();
        boolean added = false;

        try {
            if (findID(c.getID()) == null) {
                try (BufferedWriter bw = new BufferedWriter(
                        new FileWriter(fitxer, true));) {
                    //Add client to file
                    bw.write(sb.append(c.getID()).append(SEPARADOR).
                            append(c.getName()).toString());
                    bw.newLine();//New line
                    bw.flush(); //Push to file
                    added = true;

                } catch (IOException e) {
                    Logger.getLogger(DaoClient.class.getName()).log(Level.SEVERE,
                            null, "Error appeding data to file" + e);
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(DaoClient.class.getName()).log(Level.SEVERE, null,
                    "Error appeding data to file" + ex);
        } finally {

        }
        return addded;
    }

异常代码

public class NoClientFound extends Exception {

    private String msg;    

    public NoClientFound() {
        super();
    }

    public NoClientFound(String msg) {
        super(msg);
        this.msg = msg;
    }

    @Override
    public String toString() {
        return msg;
    }

标签: javaexceptionerror-handling

解决方案


您可以捕获该异常并相应地处理它。当您捕获 NoClientFound 异常时,这意味着 findID(c.getID()) 为空。因此,如果不在 if 块中处理它,您可以在 catch 块中处理它。

public boolean add(Client c) {
    StringBuilder sb = new StringBuilder();
    boolean added = false;

    try {
        // call the function
        findID(c.getID());

    } catch (NoClientFound ex) {

      //handle the NoClientFound exception as you like here

       BufferedWriter bw = new BufferedWriter(
             new FileWriter(fitxer, true));
       //Add client to file
       bw.write(sb.append(c.getID()).append(SEPARADOR).
       append(c.getName()).toString());
       bw.newLine();//New line
       bw.flush(); //Push to file
       added = true;

    }catch (IOException ex) {
        Logger.getLogger(DaoClient.class.getName()).log(Level.SEVERE, null,
                "Error appeding data to file" + ex);
    }finally {

    }
    return addded;
}

推荐阅读