Skip to content

Instantly share code, notes, and snippets.

@anelson
Created August 31, 2010 10:30
Show Gist options
  • Save anelson/558846 to your computer and use it in GitHub Desktop.
Save anelson/558846 to your computer and use it in GitHub Desktop.
Choosing the right exception types, Kyiv 2010
public class UserManager {
public void AuthenticatedUser(string userName, string password) {
if (userName != _userName) {
//WTF does 'ApplicationException' mean? It means "something didn't work"
//That's not very helpful
throw new ApplicationException("Invalid username");
}
}
}
public class UserManager {
public void AuthenticatedUser(string userName, string password) {
if (userName != _userName) {
//This is better, because you're communicating "the userName parameter has something wrong with it.
//Sometimes this is enough.
throw new ArgumentException("userName", "Invalid username");
}
}
}
public class UserManager {
public void AuthenticatedUser(string userName, string password) {
if (userName != _userName) {
// This is the most specific. If you need to detect and handle this specific case,
// you need a custom exception. Most of the time, this won't be necessary, but you
// have to use your judgement
throw new InvalidUsernameException(userName);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment