I'm developing a Java web application. It is a three layered architecture:web > service > repository.I'm thinking of creating many exceptions - each specific to each individual error and in the service layer where my business logic resides I want to throw specific exceptions that is tied to the business error.And in the web layer (further up the stack where it is closer to the front end) is where I'm catching it and handling with them accordingly.Someone said to me, don't do it this way because it is bad practice and advised me to just throw one single generic business exception instead - and he was adamant he was right. When I heard this, my reaction was that it goes against all the stuff I learned in university, past experiences, and the stuff I read in common tech books.
Is it bad practice to throw multiple custom exceptions in Java?
java;exceptions;exception handling
Is it bad practice to throw multiple custom exceptions in Java?No.  It is good practice.The only situation where multiple exceptions might be a (slightly) bad idea is if there is absolutely no possibility (ever!) of catching individual exceptions; i.e. the fine-grained exceptions won't serve any functional purpose.  However, my opinion is that if you can make that assertion, then there is probably something wrong with the way that you / your team is using Java.  And the counter-argument is that sensible use of multiple custom exceptions will help you to document the APIs ... even if you are never going to do more than catch-log-and-bail-out at runtime.This is not to say that lots of custom exceptions will always be good:If you go overboard and create a separate exception for everything, then you are probably adding unnecessary complexity.  (In a lot of cases, different exception messages are sufficient.)If you don't have a sensible inheritance hierarchy for your custom exceptions, then you may end up regretting it.  (A well-designed hierarchy allows you to catch classes of exceptions, or declare methods as throwing them.  It can make your code simpler.)