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:
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).
You can nearly never go wrong by having fine-grained exception classes that extend a common base class. That way, callers who need to specifically catch some and let others through can, and callers who want to treat them all together can do so.
I essentially agree with your current thinking.
InvalidOperationException
should indicate a bad operation w/ regards to your API, not a violation of a business rule.BadgeAuthException
, and always throw that. The specific scenarios should each get their own subclass (BadgeDeactivatedException
, NoPermissionsAtWorkstationException
, etc.) This way apps can handle the individual sub-cases separately if they want to, but they can also just catch the generic BadgeAuthException
if they don't want to grovel in specifics.Message
field always contains useful information beyond just the exception name.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With