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.

4

1 回答 1

0

只要您的程序能够检测到这些情况并从这些情况中正确恢复,使用已检查的异常来处理无效的用户输入当然是一种有效且合理的方法。已检查异常仅意味着您的程序接口需要建立并遵循关于处理程序逻辑错误的协定,而未检查(运行时)异常是以您的程序无法在运行时安全地从中恢复的方式发生的异常。您处理异常的方法可能取决于您的开发团队的理念,但检查与未检查的情况仍然存在——您知道如何检测无效输入并合理地从无效输入中恢复,因此您应该有义务对此采取措施。

有关指南,请参阅此页面:Java 中的异常。

于 2015-08-18T22:49:21.027 回答