Java 内部块的异常将由主try catch捕获,但我需要提高它们

Java 内部块的异常将由主try catch捕获,但我需要提高它们,java,nested-exceptions,Java,Nested Exceptions,当此代码引发NotFoundException时,将引发主块的异常,但我想引发NotFoundException,我如何管理它 try { if (x > y) { throw new NotFoundException("entity is not found"); } } catch (final Exception e) { throw new InternalServerErrorException(e); } 或者 这里的第一件事是,您不

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

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


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

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

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

,理想情况下,您应该以枚举所有可能的异常类型的方式编写代码,这样您就不会出现此问题。
try {
    if (x>y)
        throw new NotFoundException("entity is not found");
} catch (NotFoundException e) {
    throw e;
} catch (Exception e) {
    throw new InternalServerErrorException(e);
}
if (x > y) {
    throw new NotFoundException("entity is not found");
}