【问题标题】:why am i getting "Unhandled exception" below? [duplicate]为什么我在下面得到“未处理的异常”? [复制]
【发布时间】:2026-02-12 14:10:01
【问题描述】:
public int deleteMultipleEntries(String[] idArray) throws Exception {
    int result = dao.deleteMultipleEntries(idArray);
    cache.invalidateAll(Arrays.stream(idArray).collect(Collectors.toList()));
    if (result != idArray.length) {
        Arrays.stream(idArray).forEach(s -> {
            try {
                cache.get(s);// this method throws ExecutionException if entry with id s not found
                log.error("id:" + s + " was not deleted");
                log.info("Deleting entry id:"+Integer.valueOf(s));
                dao.deleteEntry(Integer.valueOf(s));//getting unhandled exception: java.lang.Exception error in IDE
            } catch (ExecutionException e) {
                log.info("id:" + s + " is deleted or it never existed");
            }
        });
    }
    return result;
} 
public int deleteEntry(Integer primaryKey) {
            String deleteSql = String.format(getDeleteSql(), primaryKey);
            if (log.isDebugEnabled())
                log.debug("Deleting Entry with Key: {}", primaryKey);

            int affectedRows = getJdbcTemplate().update(deleteSql);
            if (log.isDebugEnabled())
                log.debug("Updated {} Rows", affectedRows);

            return affectedRows;
        }

此语句出现错误dao.deleteEntry(Integer.valueOf(s));

如果在执行 dao.deleteEntry(Integer.valueOf(s)); 时发生异常,catch 块无法捕获异常,因为它专门捕获了 ""ExecutionException",因此函数本身应该抛出自动异常,因为它的签名有 throws 语句。 我编写的 try catch 块用于处理逻辑处理,如果我在 try catch 之外编写相同的语句,它不会给出任何错误。我想了解这里的行为。请帮忙

【问题讨论】:

  • 您必须显示deleteEntry 方法。
  • deleteEntry 可以抛出哪些类型的异常,它的throws 子句是什么?当你应该使用更具体的类型时,不要使用Exception
  • @harshalparekh : 我添加了 deleteEntry 方法

标签: java exception try-catch


【解决方案1】:

那是因为你在 Arrays.stream(idArray).forEach(...) 将其更改为正常的 foreach 即可。

public int deleteMultipleEntries(String[] idArray) throws Exception {
    int result = dao.deleteMultipleEntries(idArray);
    cache.invalidateAll(Arrays.stream(idArray).collect(Collectors.toList()));
    if (result != idArray.length) {
        for(String s: idArray) {
            try {
                cache.get(s);// this method throws ExecutionException if entry with id s not found
                log.error("id:" + s + " was not deleted");
                log.info("Deleting entry id:"+Integer.valueOf(s));
                dao.deleteEntry(Integer.valueOf(s));//getting unhandled exception: java.lang.Exception error in IDE
            } catch (ExecutionException e) {
                log.info("id:" + s + " is deleted or it never existed");
            }
        }
    }
    return result;
} 

【讨论】:

    最近更新 更多