java - 是否应该在 throws 子句中声明 IllegalArgumentException?

标签 java exception

据我了解,不需要抛出 IllegalArgumentException,因为它是运行时错误,因此理论上不应该有办法从中恢复。我的问题是应该把它扔进 throw 近距离吗?我已经尝试过了,它双向都符合。

带 throw

public static void test() throws IllegalArgumentException
{
    throw new IllegalArgumentException();
}

没有抛出

public static void test()
{
    throw new IllegalArgumentException();
}

最佳答案

正如其他人评论的那样,这是完全没有必要的,因为 IllegalArgumentException 扩展了 RuntimeException,即未经检查的异常。但是,通过将 @throws 添加到 Javadoc 来记录此行为被认为是一个好习惯,特别是当您正在开发一个将由其他人使用的库时。例如,看一下 get(int index) 的声明java.util.List 接口(interface)的方法:

/**
 * Returns the element at the specified position in this list.
 *
 * @param index index of the element to return
 * @return the element at the specified position in this list
 * @throws IndexOutOfBoundsException if the index is out of range
 *         (index < 0 || index >= size())
 */
E get(int index);

请注意,方法签名没有 throws 子句。

关于java - 是否应该在 throws 子句中声明 IllegalArgumentException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23895338/

相关文章:

java - 如何在 hql/hibernate 中的值集中使用 equals?

c++ - 代码调用终止而不是抛出异常

python 线程崩溃

c++ - 类的构造函数中的异常处理行为

java - 关于assertEquals的问题

java - 将 PDF 转换为 SWF

java - WebClient如何实现零拷贝上传下载?

java - 事件溯源中的乐观锁机制 "UNDO"流程

c# - 托管代码应该向非托管代码返回错误还是抛出异常?

java - 我应该生成异常消息吗?