[英]Cleaner way to write this try/catch block? Google App Engine
在处理事务时,我会使用try / catch。 该代码将首先尝试获取一个实体,如果捕获到EntityNotFoundException,它将尝试创建该实体。 问题是,由于我正在处理事务,因此在放置实体时还需要捕获ConcurrentModificationException。 代码看起来像这样:
try {
datastore.get(key);
} catch (EntityNotFoundException e) {
try {
datastore.put(entity);
} catch (ConcurrentModificationException e) {
// retry or log exception
}
}
虽然这看起来很丑。 我想知道是否有一种更清洁的方式来编写此代码?
您可以使用一些方法来使其保持平坦。
try {
datastore.get(key);
} catch (EntityNotFoundException e) {
createEntity(entity);
}
private void createEntity(Object entity){ //Replace Object with the correct type
try{
datastore.put(entity);
}catch (ConcurrentModificationException e) {
//Handling both errors
}
}
这将使try-catch-blocks有点解开。
尝试创建一个单独的方法,例如
public static KeyValue get(DataStore datastore, Key key){ //assume this method is in Util class
try {
return datastore.get(key);
} catch (EntityNotFoundException e) {
return null;
}
}
//现在执行
KeyValue value = Util.get(datastore, key);
if(value!=null){
// do your steps
}
else{
// create
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.