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

68 Views Asked by At

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

There are 2 best solutions below

0
sstan On BEST ANSWER
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);
}
0
barunsthakur On

The first thing here is that you don't need the try catch block. You could just use

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

Obviously the inner exception in your code will be caught in the try catch block so rather than catching Exception in your catch block, You can catch some more specific Exception. For example if a block of code is expected to throw IOException, rather than catching Exception you should catch IOException