When to use custom exceptions vs. existing exceptions vs. generic exceptions
- by Ryan Elkins
I'm trying to figure out what the correct form of exceptions to throw would be for a library I am writing. One example of what I need to handle is logging a user in to a station. They do this by scanning a badge. Possible things that could go wrong include:
Their badge is deactivated
They don't have permission to work at this station
The badge scanned does not exist in the system
They are already logged in to another station elsewhere
The database is down
Internal DB error (happens sometimes if the badge didn't get set up correctly)
An application using this library will have to handle these exceptions one way or another. It's possible they may decide to just say "Error" or they may want to give the user more useful information. What's the best practice in this situation? Create a custom exception for each possibility? Use existing exceptions? Use Exception and pass in the reason (throw new Exception("Badge is deactivated.");)? I'm thinking it's some sort of mix of the first two, using existing exceptions where applicable, and creating new ones where needed (and grouping exceptions where it makes sense).