簡體   English   中英

內部塊的異常將被主 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塊被捕獲如此,而不是捕捉Exception在catch塊,你可以捕捉一些更具體的異常。 例如,如果一個代碼塊應該拋出IOException ,而不是捕捉Exception你應該捕捉IOException

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM