Alex Rivera | Logout

When to use custom exceptions vs. existing exceptions vs. generic exceptions

Asked 2010-04-06T20:57:40.500
13

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

Edit
Report

1 Answer

9

Use Exception and pass in the reason (throw new Exception("Badge is deactivated.");)

This certainly is a bad practice, because it violates the purpose of exceptions - not just to signal an abnormal situation, but provide an ability to distinguish exceptions on a type level, so the user of a module can make a decision depending on a type of exception.

Generally, it is good to reuse standard exceptions as far as they can fully describe abnormal situations your code actually faces. It is quite hard to give an advise in a current situation, because exceptions can often depend on semantics ( argument exception or invalid operation exception (maybe suitable for 'Their badge is deactivated' case, for example ).

answered 2010-04-06T21:04:07.457

Your Answer