[英]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.