Java接口抛出异常最佳实践 [英] Java interface throws Exception best practice

查看:406
本文介绍了Java接口抛出异常最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在定义一个新的界面API ...诚然,我不是经常做的事情。我想定义接口方法来抛出异常以允许实现者的一些灵活性。然后他们可以选择抛出一个异常,抛出一个更具体的异常子类,或者什么也不做。我已经阅读了几次,虽然它很好地允许实现类这个灵活性,但是使用throws Exception定义接口方法也是不好的。相反,建议将异常(例如MyException)子类化并抛出子类。对这种做法的解释缺乏细节,有人可以详细说明这个最佳做法吗?谢谢。

I'm defining a new interface API... admittedly not something I do all that often. I'd like to define the interface methods to throw an Exception to allow some flexibility for the implementers. They can then choose to throw an Exception, throw a more specific subclass of Exception, or throw nothing at all. I've read a couple of times that while its good to allow implementing classes this flexibility, it's also bad to define the interface method with "throws Exception". Instead, it's recommended to subclass Exception (e.g. MyException) and throw the subclass. The explanations for this practice were lacking in detail, so can someone elaborate on this best practice please? Thanks.

推荐答案

我可以体会到让实现者有一些灵活性,但是 异常是API, ,所以你应该考虑什么(检查)异常是有意义的。

I can appreciate trying to give the implementers some flexibility, but the exception is part of the API, so you should put some thought into what (checked) exception(s) makes sense.

通过说 throws Exception ,你没有帮助接口的客户端了解什么样的故障会让他们有机会对他们做出适当的反应。您可以考虑类似于接受 Object 的方法参数,以允许实现者决定他们可以接受的参数。它对实现者有好处,但对于接口的客户端来说是一场恶梦。

By saying throws Exception, you are not helping the clients of the interface understand what kinds of failures are expected to give them a chance to react to them appropriately. You can consider akin to accepting a method parameter of Object to allow implementers to decide what arguments they can accept. Its good for the implementer, but a nightmare for the clients of the interface.

这篇关于Java接口抛出异常最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆