2014-05-07 17 views
0

我從Twitter檢索數據。我存儲了一些數據庫中的ID,我試圖通過twitter API檢索信息。我使用下面的代碼:Try-catch問題與Twitter API身份驗證

if(cursor.hasNext()){ 
    try { 
     while (cursor.hasNext()) { 

      final DBObject result = cursor.next(); 
      JSONObject features = new JSONObject(); 

      //System.out.println(result); 
      Map<String, Object> value = (Map<String, Object>) result.get("user"); 
      boole.add((Boolean) value.get("default_profile")); 
      boole.add((Boolean) value.get("default_profile_image")); 

      features.put("_id", value.get("id")); 
    ... 
    } 
catch (JSONException e) { 
      System.err.println("JSONException while retrieving users from db: " + e); 
     } catch (TwitterException e) { 
      // do not throw if user has protected tweets, or if they deleted their account 
      if (e.getStatusCode() == HttpResponseCode.UNAUTHORIZED || e.getStatusCode() == HttpResponseCode.NOT_FOUND) { 


      } else { 
       throw e; 
      } 
     } 

我添加Twitter的例外,因爲我不能檢索一些用戶因認證問題的數據。但是,當我的代碼到達catch(TwitterException e)它會自動停止運行。我想繼續到下一個遊標(下一個數據庫的ID)

回答

1

這是因爲你已經在你的循環中嘗試了catch塊,所以當異常被捕獲時,它就會脫離循環。

放置嘗試catch塊,而塊將解決問題。

1

如果您想這樣做,您需要將try-catch塊移動到while之內。目前,一旦在while中拋出異常,它將退出while並轉至catch塊,並在此後停止執行。如果在while內移動try,則即使在引發和處理異常之後,while也會繼續。

循環和try-catch應該像這樣構造。

while (cursor.hasNext()) { 
    try { 
     // The code 
    } 
    catch (JSONException e) { 
     // your code 
    } 
    catch (TwitterException e) { 
     // your code 
    } 
}