在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 extends
在Exception class
时的实现
现在我需要根据runtime exception
处理更改save方法
问题:
如果不使用
try catch
方法,我如何更改此方法如果没有try-catch,如何处理
exception
# 1 楼答案
RuntimeException
不必在方法签名中声明,如果您也想删除try/catch块,可以这样做:当没有try/catch时,异常不会被“处理”,而是被级联,直到更高级别处理它,或者直到程序存在最高级别(使用
RuntimeException
)# 2 楼答案
Runtime exceptions
不需要被抓到。如果使用AppException
作为选中的异常,仍然不需要放置try/catch
,因为您已经在方法签名中使用throws
处理了它。调用save()
的方法必须处理AppException