Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use custom exceptions vs. existing exceptions vs. generic exceptions [closed]

Tags:

exception

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).

like image 444
Ryan Elkins Avatar asked Apr 06 '10 20:04

Ryan Elkins


2 Answers

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.

like image 51
bmargulies Avatar answered Oct 01 '22 16:10

bmargulies


I essentially agree with your current thinking.

  • Use existing core exceptions where appropriate: ArgumentException, InvalidOperationException, etc. Don't try to repurpose exceptions that are specific to some other module. Use those exceptions that have a clear, generic purpose, and don't use them for business rules. For example, InvalidOperationException should indicate a bad operation w/ regards to your API, not a violation of a business rule.
  • For exceptions specific to your library, create a base exception class, 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.
  • Whatever you do, ensure that the Message field always contains useful information beyond just the exception name.
like image 32
JSBձոգչ Avatar answered Oct 01 '22 17:10

JSBձոգչ