简体   繁体   中英

Cleaner way to write this try/catch block? Google App Engine

I use a try/catch when working with transactions. The code would first try to get an entity and if it catches an EntityNotFoundException, it would try to create the entity. The problem is, since I am working with transactions, I also need to catch ConcurrentModificationException when putting the entity. The code looks somewhat like this:

try {
   datastore.get(key);
} catch (EntityNotFoundException e) {
   try {
      datastore.put(entity);
   } catch (ConcurrentModificationException e) {
      // retry or log exception
   }
}

This looks pretty ugly though. I was wondering if there is a cleaner way to write this?

You can work with methods to keep it flat.

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
    }
}

This will untangle the try-catch-blocks a little bit.

Try to create a separate method Eg

  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;
          }
       }

// now implementation

       KeyValue value = Util.get(datastore, key);

         if(value!=null){

                     // do your steps
          }
         else{
               // create
         }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM