-1

当此代码引发NotFoundExceptionmain 块的异常时,将引发异常,但我想 raise NotFoundException,我该如何管理它?

try {
    if (x > y) {
        throw new NotFoundException("entity is not found");
    }
} catch (final Exception e) {
    throw new InternalServerErrorException(e);
}
4

2 回答 2

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);
}
于 2015-06-29T19:02:44.787 回答
0

这里的第一件事是您不需要 try catch 块。你可以使用

if (x > y) {
    throw new NotFoundException("entity is not found");
}

显然,代码中的内部异常将在 try catch 块Exception中捕获,因此您可以捕获一些更具体的异常,而不是在 catch 块中捕获。例如,如果期望一个代码块抛出IOException,而不是捕捉Exception你应该捕捉IOException

于 2015-06-29T19:13:32.440 回答