据我了解,不需要抛出 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/