Search code examples
javanested-exceptions

Exception of internal blocks will be catch by main try-catch but i need to raise them


When this code raise NotFoundException the exception of main block will be raised, but I would like to raise NotFoundException, how can I manage it?

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

Solution

  • 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);
        }
    }
    

    or...

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