Why is it discouraged to throw a generic (java.lang.Exception) exception, when it is usually sufficient to handle most conditional failures within a method? I understand tha
Dittos to GH. I would have used "null pointer exception" and "out of memory exception" as more obvious examples of the kind of exceptions you probably don't watch to catch in the same block with your true application exceptions.
I'd also add that it pays to go to a little effort for future expandability. If you throw generic Exceptions all over the place, and later you decide that you need to catch some exceptions and not others, it can be a major pain to go back and change them all. But if you just create the exceptions you need as you go along, it's not that big a deal. Creating a new exception class that just accepts a constructor with a message takes, what, 5 lines of code? It's good investment for the future.
Like many things in programming, it's a question of how far you go. I usually create a rather generic "BadInputException" in almost every project I work on, and throw this any time user inputs fail validation criteria. Then I can just catch BadInputException and throw the message on the screen. If I create a complex class that throws exceptions for inconsistent data and that sort of thing, I usually create an exception class for it. Like if I create a "TalkToDatabase" class, I'll create a "TalkToDatabaseException". (Maybe more than that if there are multiple kinds of exceptions I know I want to catch, but at least the one.)
And by the way, I don't know if you're thinking of this, but I would strongly discourage examining the text of an error message to determine the type of error. I've seen programs where they throw generic Exceptions all over the place, and then in catch blocks they have code like
// Very bad idea! Don't do this!
catch (Exception ex)
{
if (ex.getMessage().equals("Invalid foo"))
... handle bad foo ...
else if (ex.getMessage().equals("Plugh is over maximum"))
... handle bad plugh ...
... etc ...
}
It would be much better to just make separate Exceptions for these cases. Not only will processing be much more efficient, but suppose you do the above and somebody comes along later and decides to change the message to "Foo is invalid"? The program will still compile, but it won't work correctly.