本文介绍了我应该使用相关的内置非检查异常,其中理论规定使用检查的异常吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于已检查和未检查的异常主题,SO上有不少帖子。 可能是最全面和最丰富的信息。然而,我仍然存在冲突,遵循这里提出的逻辑,并且有一个原因。



我正在围绕一组类似于每个服务的一组服务构建一个包装API其他。然而,它们之间存在微小的差异(或将来的可能性),从而某些服务可能支持某些功能(次要和捷径性质),而不被其他服务支持。因此,以下方法似乎是符合逻辑的:

  public interface GenericWrapperInterface {
void possibleUnsupportedOperation()throws java .lang.UnsupportedOperationException;
}

为什么 UnsupportedOperationException ?因为它是为这种情况设计的。



然而,除了Oracle的,假设如果使用异常来表示客户端可以从中恢复的问题或问题可预测但不可避免,那么该例外应该是一个检查的例外。我的情况符合这些要求,因为一些操作可能提前知道它们不可用的可能性,这些操作并不重要,如果需要可以避免。



所以我迷失在这个难题中我应该使用一个完美的标准异常,违反了异常使用的常见逻辑,还是应该建立自己的检查选项,从而重复代码,并在API用户之间创造额外的混乱?

解决方案

UnsupportedOperationException表示Java OO模型的失败,特别是违反了Liskov的原则。



通常,这意味着您的代码有其他非OO方法来决定是否应该调用相关方法:

  if instance.isSupportive())instance.possiblyUnsupportedOperation(); 

因此,调用未实现的方法是一个逻辑错误,与断言失败,堆栈溢出或运行内存不足。因此,它不应该是被检查的例外。


There are quite a few posts on SO about the "checked vs unchecked exception" topic. This answer is probably the most well-rounded and informative. Yet I'm still conflicted to follow the logic presented there, and there's a reason for that.

I'm building a wrapper API around a set of services similar to each other. There are, however, minor differences between them (or a possibility of such in the future), so that certain functions (of secondary and shortcut nature) may be supported by some services and not supported by others. So it seems only logical to go with the following approach:

public interface GenericWrapperInterface {
    void possiblyUnsupportedOperation () throws java.lang.UnsupportedOperationException;
}

Why UnsupportedOperationException? Because it is designed exactly for this kind of situations.

However, all the relevant SO posts, in addition to Oracle's own manual, postulate that if an exception is used to signal an issue that the client could recover from, or an issue predictable but unavoidable, then that exception should be a checked one. My case conforms to these requirements, because for some operations the possibility of their unavailability may be known in advance and those operations are not critical and may be avoided if needed.

So I'm lost in this conundrum. Should I go with a perfectly fitting standard exception and violate the common logic of exception usage, or should I build my own checked alternative and thus duplicate code and create additional confusion among the API users?

解决方案

The "UnsupportedOperationException" denotes a failure of Java OO model, in particular, a violation of Liskov's Principle.

Usually, that means your code has other, non-OO means to decide if the method in question should be called:

if (instance.isSupportive()) instance.possiblyUnsupportedOperation();

Therefore, calling an unimplemented method is a logic error, on par with assertion failure, stack overflow or running out of memory. As such, it should not be a checked exception.

这篇关于我应该使用相关的内置非检查异常,其中理论规定使用检查的异常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 06:20