I saw how this topic sometimes appeared in the past, but even after Googling about it , I still canโt understand what being a good and elegant way to deal with it, so here it is.
Say I have code that throws various exceptions ...
try { } 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 transfer these exceptions and throw a new one, saying that something went wrong in my API.
It seems to me that the code is too repetitive, so you just catch the type of exception and process it with a shell and throw away a new one.
try { } catch (Exception e) { throw new MyAPIException("Something went wrong", e); }
In this case, it will be much simpler, but the fact is that we will also catch every RuntimeException. Given this, we could catch a RuntimeException to avoid this.
try { } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new MyAPIException("Something went wrong", e); }
Its a little cumbersome, but it does the trick. Now one more minor problem with catch (Exception e) is that if my internal API throws another MyAPIException, it will also be caught, wrapped and thrown into another MyAPIException. In this particular case, we could also catch a MyAPIException and throw it again.
try { } catch (RuntimeException e) { throw e; } catch (MyAPIException e) { throw e; } catch (Exception e) { throw new MyAPIException("Something went wrong", e); }
Well, it gets dirty again, but in this case we prevent a MyAPIException wrap and just throw it again. But, in addition, there is another problem with the catch (Exception e) block, which, if the internal API changes and starts throwing a different kind of exception (some other than the above 4), the compiler did not say anything about it, and we would have there is a key. Not that this was a serious problem, since I probably would have looked at it the same way.
In this scenario, I think the question is which one is better, and are there any better options?