0

I have an operation/method that performs an insert to a database. It takes several fields and for various reasons that operation could fail because one or more of the inputs was not unique or because they conflict with some internal records that need to be unique.

saveUserInfo(primaryToken,secondaryToken,userid);

Would it make sense for me to throw a checked exception on each violation?

My thinking was to use the following:

saveUserInfo(String primaryToken, String secondaryToken, String id) 
throws PrimaryTokenTakenException,SecondaryTokenTakenException

forcing any developer that calls this method to deal with it by routing the web user to a page asking for a new token.

Opposition The opponents of this approach point out that we, the dev team, are aware of each of the error cases that would cause this to fail and should instead return an error code and use that to handle each case.

int errorCode = saveUserInfo(primaryToken,secondaryToken,userid);

I don't see any obvious drawbacks to the checked approach. These error cases are very likely to happen and you absolutely must address them anywhere saveUserInfo() is used. It seems like exactly the situation checked exceptions were created for.

Usman Mutawakil
  • 4,993
  • 9
  • 43
  • 80

1 Answers1

0

It's certainly a valid and reasonable approach to use checked exceptions to handle invalid user input, so long as your program is able to detect and properly recover from those cases. Checked exceptions just mean that your program interfaces need to establish and follow a contract with respect to handling program logic errors, whereas unchecked (runtime) exceptions are exceptions that occur in such a manner that your program cannot safely recover from them at runtime. The method in which you handle the exceptions can depend on your dev team's philosophy, but the checked vs unchecked case still holds -- you know how to detect and reasonably recover from an invalid input, so you should be obligated to do something about it.

See this page re: exceptions in Java, for a guide.

Ryan J
  • 8,275
  • 3
  • 25
  • 28