-1

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);
}
barunsthakur
  • 1,196
  • 1
  • 7
  • 18
Fariba
  • 693
  • 1
  • 12
  • 27
  • Ideally you should write your code in such a way which enumerates all the possible exception types, and then you would not have this issue. – aestrivex Jun 29 '15 at 19:12

2 Answers2

1
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);
}
sstan
  • 35,425
  • 6
  • 48
  • 66
0

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

barunsthakur
  • 1,196
  • 1
  • 7
  • 18