In a standard J2EE web application , assuming that class load times during app startup is not an issue, which would be a better approach in terms of maintainance, performace and usability ?
The first approach involves creating different exception classes, each to denote a particular error that occurs in the application. The class names are self explanatory, and that'll be used to provide error messages. (UPDATE : The number of classes is about 30 as of now, and it'll continue to increase in the near future, probably upto 70 or 80 atmost)
The secodn approach involves creating one exception class, and a bunch of exception codes where each code represent a particular error in the app. The error codes are obtained from the exception, and is used to provide error messages.
It is more or less dependent on your business needs. From my point of view, having multiple custom exception classes is the right approach to go.
Learn from Java, how many it manages.
In any given application there can be n types of validation requirements, some can be represented under one group and some into another, but fitting everything into single does not serve the intended purpose in terms of logic and business.
Let's say we have a class called UserAuthenticationException
.
This exception can represent multiple different error conditions and give different messages for each case; for example:
1.) Invalid username/passwords
2.) Session timeout
3.) Multiple active token of same user in different machines etc...
Handling errors with instanceof
and handlers for each exception class is much easier than handling errors based on error messages.