Hello,
I've seen this topic arise sometimes in the past but even after Googling about it, I still can't figure out what would be a good and elegant way to deal with it, so here it goes.
Say I have some code that throws various exceptions...
try {
/* some code that throws these exceptions */
} catch (NoSuchAuthorityCodeException e) {
throw new MyAPIException("Something went wrong", e);
} catch (FactoryException e) {
throw new MyAPIException("Something went wrong", e);
} catch (MismatchedDimensionException e) {
throw new MyAPIException("Something went wrong", e);
} catch (TransformException e) {
throw new MyAPIException("Something went wrong", e);
}
... and as we can see, I just wrap these exceptions and throw a new one saying that something went wrong within my API.
This seems to me a overly repetitive code, so one would simply catch an Exception type and handle wrap it and throw a new one.
try {
/* some code that throws these exceptions */
} catch (Exception e) {
throw new MyAPIException("Something went wrong", e);
}
In this case it stays way more simpler, but the thing is we'd be catch also every RuntimeException. Given this, we could catch-re-throw the RuntimeException so we could avoid this.
try {
/* some code that throws some exceptions */
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new MyAPIException("Something went wrong", e);
}
Its a bit bulky but it does the trick. Now theres another little issue about the catch(Exception e), that if my inner API throws another MyAPIException it would also be caught, wrapped and throwed within another MyAPIException. In this particular case we could also catch MyAPIException and re-throw it.
try {
/* some code that throws some exceptions */
} catch (RuntimeException e) {
throw e;
} catch (MyAPIException e) {
throw e;
} catch (Exception e) {
throw new MyAPIException("Something went wrong", e);
}
Well, its getting messy again, but in this case we prevent wrapping MyAPIException and simply re-throw it. But, theres also another issue with the catch (Exception e) block that is if the inner API changes and start throwing another kind of exception (some other than these 4 mentioned above), the compiler wouldn't say anything about it and we wouldn't have a clue. Not that this would be a major problem, since probably I would treat it in the same manner.
With this scenario, I think the question is, which one is better and are there better options?