java - 我该如何处理这个自定义异常?
问题描述
我有这段代码,它依赖于一个函数抛出的自定义异常,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;
}
解决方案
您可以捕获该异常并相应地处理它。当您捕获 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;
}
推荐阅读
- python - 如何修复''在位置 2 没有重复的内容''
- ansible - 为什么 Ansible 会忽略我的库存文件?
- django - 权限类装饰器被忽略。“未提供身份验证凭据”响应
- sql - PostgreSQL group_concat 行作为 json
- ios - FaceID动画完成后如何准确回调?
- python-3.x - 从网页中提取 URL 链接
- java - Java getter setter 无法存储值
- amazon-cloudfront - 使用 aws cli 在 extsting 云端分发中添加额外的来源和行为
- mongodb - 快速查询MongoDB的数据结构设计
- swift - 任何人都可以帮助我如何从给定的示例中获得价值,因为我是 swift 新手