简短的回答是,它根据您的域名,客户以及您提供的具体情况而有很大差异。如果你还没有,你需要坐下来与你的客户,并找出他们将如何使用图书馆。刚刚离开我的头顶,这里有一些我会考虑的事情:
首先,您确定的所有故障类型基本上是相同的东西 - UnsupportedOperationException
,原因是什么。是否有其他故障类型?如果不是,并且您使用异常,则可能需要一个类型为/ cause/whatever的异常类作为枚举属性。其次,它看起来很多/大多数/所有的方法将会有一个或多个类似的失败类型。真的吗?如果是这样,您的API是否提供了确定设备支持哪些功能的方法?试想一下:
// Best if I probably don't care about the result if it's not SUCCESS
final Result result = myApiObject.someMethod();
if (result == Result.BEEP_UNSUPPORTED) {
....
} else if (result == Result.NO_DISPLAY) {
....
} else if ...
这:
// Best if I have to handle every possible failure condition, and I care what
// the failure type is
try {
myApiObject.someMethod();
} catch (final BeepUnsupportedException e) {
....
} catch (final NoDisplayException e) {
....
}
这:
// Best if I have to consider every possible failure condition, but it probably
// doesn't matter what the failure type is
try {
myApiObject.someMethod();
} catch (final MyApiException e) {
if (Cause.BEEP_UNSUPPORTED == e.getCause()) {
....
} else ....
这:
// Best if I know in advance what features I may need
// someMethod() may still return response codes or throw an exception. In this case
// it's possibly OK to make it a RuntimeException, since clients are expected to
// poll for features.
if (myApiObject.supports(Feature.BEEP)
&& myApiObject.supports(Feature.DISPLAY)) {
myApiObject.someMethod();
} else ...
哪一个是最接近的方式你的客户会想要使用你的系统?
三,这些错误有多致命?我完全同意@Harmlezz必须处理的故障必须是异常。没有更多的信息,我们谁都不能告诉你,你的失败是否需要处理。如果客户大多会忽视失败(他们通常希望代码失败),或者只是主要关心SUCCESS
或!SUCCESS
,那么返回代码可能没问题。如果故障需要来处理,那么你应该抛出一个检查异常。您可能希望远离未经检查的异常,因为这些失败不是编程错误,并且可能由客户端正确处理。
java.lang.Enum? – esej
除了成功,我只看到多种类型的失败。为什么这些不能包含在例外中? – nablex
枚举或int标志。还有同样的问题。失败可能是半预期的。即操作不受支持。异常会改变流程,我的理解只能用于异常/意外状态。 – conor