Java 为什么GenericObjectPool.addObject引发选中异常
Apache的(有用的)org.Apache.commons.pool.impl.commmons.pool.GenericObjectPool.addObject()被声明为抛出异常有什么好的理由吗Java 为什么GenericObjectPool.addObject引发选中异常,java,apache-commons,Java,Apache Commons,Apache的(有用的)org.Apache.commons.pool.impl.commmons.pool.GenericObjectPool.addObject()被声明为抛出异常有什么好的理由吗 /** * Create an object, and place it into the pool. * addObject() is useful for "pre-loading" a pool with idle objects. */ @Override public void a
/**
* Create an object, and place it into the pool.
* addObject() is useful for "pre-loading" a pool with idle objects.
*/
@Override
public void addObject() throws Exception {
assertOpen();
if (_factory == null) {
throw new IllegalStateException("Cannot add objects without a factory.");
}
T obj = _factory.makeObject();
try {
assertOpen();
addObjectToPool(obj, false);
} catch (IllegalStateException ex) { // Pool closed
try {
_factory.destroyObject(obj);
} catch (Exception ex2) {
// swallow
}
throw ex;
}
}
实际上,org.apache.commons.pool.BaseObjectPool在org.apache.commons.pool接口中声明了它:
/**
* Create an object using the {@link PoolableObjectFactory factory} or other
* implementation dependent mechanism, passivate it, and then place it in the idle object pool.
* <code>addObject</code> is useful for "pre-loading" a pool with idle objects.
* (Optional operation).
*
* @throws Exception when {@link PoolableObjectFactory#makeObject} fails.
* @throws IllegalStateException after {@link #close} has been called on this pool.
* @throws UnsupportedOperationException when this pool cannot add new idle objects.
*/
void addObject() throws Exception, IllegalStateException, UnsupportedOperationException;
为什么不使用RuntimeException的派生
/**
* Create an object, and place it into the pool.
* addObject() is useful for "pre-loading" a pool with idle objects.
*/
@Override
public void addObject() throws Exception {
assertOpen();
if (_factory == null) {
throw new IllegalStateException("Cannot add objects without a factory.");
}
T obj = _factory.makeObject();
try {
assertOpen();
addObjectToPool(obj, false);
} catch (IllegalStateException ex) { // Pool closed
try {
_factory.destroyObject(obj);
} catch (Exception ex2) {
// swallow
}
throw ex;
}
}
好的,直接的答案就在Javadoc中:
@throws Exception when {@link PoolableObjectFactory#makeObject} fails.
(旁白:工厂接口实际上似乎是PooledObjectFactory
,而不是pooleable
)
那么,为什么makeObject抛出异常呢?对象池的一个常见用例是池数据库连接,创建和销毁数据库连接的成本很高,并且(曾经?)有时受到软件许可(N-connection许可)的限制。创建新的数据库连接可能引发SQLException,如果数据库服务器位于远程计算机上,则可能引发IOException。makeObject被声明为引发异常,因此在尝试将连接放入池或从池中检索连接时,可以传递并捕获这些已检查的异常。您至少需要跟踪诸如addObjectToPool和destroyObject之类的调用,以查看其中一个或多个是否引发异常。为什么呢?谁知道。。。但是抛出RuntimeException也不是一个好主意。