当此代码引发NotFoundException
main 块的异常时,将引发异常,但我想 raise NotFoundException
,我该如何管理它?
try {
if (x > y) {
throw new NotFoundException("entity is not found");
}
} catch (final Exception e) {
throw new InternalServerErrorException(e);
}
当此代码引发NotFoundException
main 块的异常时,将引发异常,但我想 raise NotFoundException
,我该如何管理它?
try {
if (x > y) {
throw new NotFoundException("entity is not found");
}
} catch (final Exception e) {
throw new InternalServerErrorException(e);
}
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);
}
这里的第一件事是您不需要 try catch 块。你可以使用
if (x > y) {
throw new NotFoundException("entity is not found");
}
显然,代码中的内部异常将在 try catch 块Exception
中捕获,因此您可以捕获一些更具体的异常,而不是在 catch 块中捕获。例如,如果期望一个代码块抛出IOException
,而不是捕捉Exception
你应该捕捉IOException