3
donuts
6y

Ok so Sonar had a rule that you should not throw Exception. Rather you should always throw a specific types or catch them...

I don't understand this. So if the underlying function throws 10 different types of exceptions then the calling function should also declare it throws 10 different types rather than just Exception?

Assuming it isn't in a position to handle them?

Comments
  • 0
    And for example IOException is OK but there are many kinds of IOException too....

    So why can't I just declare a method throws Exception rather than IOException or the specific kinds of IOException.

    In runtime, even if I catch an Exception, it will still show the specific type in the logs so if I want more granular handling, I just add another catch for that specific type... But I'm not going to care until it causes an error and again by that time I will know what the specific error is.

    And that latter case is rare anyway? 95%+ of exceptions are handled under catch(Exception e).
  • 1
    This is a bit of a short answer, but essentially you shouldn’t really do catch(Exception e) because sometimes you want the program to crash (or probably not totally crash but have some outer try-catch block that says “sorry it’s all fucked” in some way and then quits).

    By telling you what specific exception types to expect, you can choose to deal with them but without accidentally suppressing something major.
Add Comment