的Java API的设计 - NULL或异常 [英] java api design - NULL or Exception

查看:244
本文介绍了的Java API的设计 - NULL或异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是更好地从API方法返回空值或者抛出一个异常?

Is it better to return a null value or throw an exception from an API method?

返回一个空需要丑陋null检查全部结束,并导致重大质量问题,如果没有选中的回报。

Returning a null requires ugly null checks all over, and cause a major quality problem if the return is not checked.

抛出异常强制用户code为故障的条件,但由于Java异常冒泡并强制主叫code来处理它们,在一般情况下,使用自定义异常可能是一个坏主意(特别在Java)。

Throwing an exception forces the user to code for the faulty condition, but since Java exceptions bubble up and force the caller code to handle them, in general, using custom exceptions may be a bad idea (specifically in java).

任何声音和实用的建议?

Any sound and practical advice?

推荐答案

我想答案是完全依赖于你的应用程序,你认为是一个特殊情况与编程错误什么的背景下,和

I think the answer is entirely dependent on the context of your application, and what you consider to be an "exceptional circumstance" versus programmer error.

例如,如果编写XML解析器,你可以选择实施类似的方法:

For example, if writing an XML parser you may choose to implement methods like:

/**
 * Returns first child element with matching element name or else
 * throws an exception.  Will never return null.
 */
Element getMandatoryChildElement(Element parent, String elementName)
throws MissingElementException;

...因为这种方法可以让你实现你的消息解析code逻辑单块,而无需检查检索每个元素或属性后是良好的成形消息。

... as this approach allows you to implement your message parsing code in a single block of logic, without having to check that the message is well-formed after retrieving each element or attribute.

这篇关于的Java API的设计 - NULL或异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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