java 在 javadoc 中,@throws 和 @exception 标签有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5510170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:28:28  来源:igfitidea点击:

In javadoc, what is the difference between the tags @throws and @exception?

javajavadoc

提问by jon2512chua

Take the following implementation of a array-based stack of chars for example:

以以下基于数组的字符堆栈的实现为例:

public char peek() throws Underflow {
    if (!isEmpty()) {
        return stack[pos];
    } else {
        throw new Underflow("Peeking at an empty stack.");
    }
}

Back when I'm using just a text editor I always use the @exception tag, but now my IDE (Netbeans) used @throws when generating the javadoc.

当我只使用文本编辑器时,我总是使用 @exception 标记,但现在我的 IDE(Netbeans)在生成 javadoc 时使用了 @throws。

So my question is, what is the difference between the two and when should one be preferred over another (using the above code for example)?

所以我的问题是,两者之间有什么区别,什么时候应该优先于另一个(例如使用上面的代码)?

回答by T.J. Crowder

There is none, they're synonyms. From the docs:

没有,它们是同义词。从文档

Documenting Exceptions with @throwsTag
NOTE - The tags @throwsand @exceptionare synonyms.

@throws标签记录异常
注意 - 标签@throws@exception是同义词。

回答by Hardik Mishra

@throwswas added because it is a keyword ("throws" clause in a method declaration),

@throws添加是因为它是一个关键字(方法声明中的“throws”子句),

and, as a verb, it is just more natural to read. This reads as a sentence:

而且,作为动词,读起来更自然。这读作一句话:

@throws NullPointerException

while this seem more redundant:

虽然这看起来更多余:

@exception NullPointerException

Otherwise, both are synonyms

否则,两者都是同义词

回答by combinatorics

@exceptionisn't 100% correct if you code throws a Throwable. @throwsis more exact. (I realize there isn't a good use case for ever using throw new Throwable(), but theoretically it is allowed.)

@exception如果您的代码抛出一个Throwable. @throws更准确。(我意识到永远使用 没有一个好的用例throw new Throwable(),但理论上它是允许的。)