有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在java中将方法更改为运行时异常

我有一个方法,现在我正在使用try-catch方法处理异常

我有一个自定义的异常方法来处理错误

现在我必须将这个异常处理更改为运行时异常

代码:

public class AppException extends RuntimeException {

    private static final long serialVersionUID = -8674749112864599715L;

    public AppException() {
    }

    public AppException(String message, Throwable cause,
            boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }

    public AppException(String message, Throwable cause) {
        super(message, cause);
    }

    public AppException(String message) {
        super(message);
    }

    public AppException(Throwable cause) {
        super(cause);
    }
}

使用try-catch处理的方法

@Transactional(readOnly = false)
@Override
public String save(StagingDocument stagingData)
        throws AppException {
    String enrichObjectId = null;
    try {
        EnrichDocument document = getEnrichDocument(stagingData);
        EnrichDocument enrichPayload = enrichStagingDocumentRepository
                .save(document);
        enrichObjectId = enrichPayload.getId().toString();
    } catch (Exception e) {
        logger.error("EXCEPTION IN SAVETOENRICHDOCUMENT METHOD: " + e);
        throw new AppException (e.getMessage(), e.getCause());
    }
    return enrichObjectId;
}

在上面的方法中,这里是AppException extendsException class时的实现

现在我需要根据runtime exception处理更改save方法

问题:

  1. 如果不使用try catch方法,我如何更改此方法

  2. 如果没有try-catch,如何处理exception


共 (2) 个答案

  1. # 1 楼答案

    RuntimeException不必在方法签名中声明,如果您也想删除try/catch块,可以这样做:

    @Transactional(readOnly = false)
    @Override
    public String save(StagingDocument stagingData) {
            String enrichObjectId = null;
            EnrichDocument document = getEnrichDocument(stagingData);
            EnrichDocument enrichPayload = enrichStagingDocumentRepository
                    .save(document);
            enrichObjectId = enrichPayload.getId().toString();
            return enrichObjectId;
    }
    

    当没有try/catch时,异常不会被“处理”,而是被级联,直到更高级别处理它,或者直到程序存在最高级别(使用RuntimeException

  2. # 2 楼答案

    Runtime exceptions不需要被抓到。如果使用AppException作为选中的异常,仍然不需要放置try/catch,因为您已经在方法签名中使用throws处理了它。调用save()的方法必须处理AppException