内部块的异常将被主 try-catch 捕获,但我需要引发它们
Exception of internal blocks will be catch by main try-catch but i need to raise them
当这段代码引发NotFoundException
主块的异常时会引发,但我想引发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 块中捕获,因此您可以捕获一些更具体的异常,而不是在 catch 块中捕获 Exception
。例如,如果一段代码预计会抛出 IOException
,而不是捕获 Exception
,您应该捕获 IOException
当这段代码引发NotFoundException
主块的异常时会引发,但我想引发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 块中捕获,因此您可以捕获一些更具体的异常,而不是在 catch 块中捕获 Exception
。例如,如果一段代码预计会抛出 IOException
,而不是捕获 Exception
,您应该捕获 IOException