当此代码引发NotFoundException
时,将引发主程序段的异常,但我想提出NotFoundException
,我该如何管理它?
try {
if (x > y) {
throw new NotFoundException("entity is not found");
}
} catch (final Exception e) {
throw new InternalServerErrorException(e);
}
答案 0 :(得分:1)
try {
if (x>y)
throw new NotFoundException("entity is not found");
} catch (Exception e) {
if (e instanceof NotFoundException) {
throw e;
} else {
throw new InternalServerErrorException(e);
}
}
...或
try {
if (x>y)
throw new NotFoundException("entity is not found");
} catch (NotFoundException e) {
throw e;
} catch (Exception e) {
throw new InternalServerErrorException(e);
}
答案 1 :(得分:0)
这里的第一件事是你不需要try catch块。你可以使用
if (x > y) {
throw new NotFoundException("entity is not found");
}
显然,代码中的内部异常将被捕获在try catch块中,而不是在catch块中捕获Exception
,您可以捕获一些更具体的异常。例如,如果一个代码块应该抛出IOException
,而不是捕获Exception
,那么你应该抓住IOException