有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

twitter api身份验证的java Trycatch问题

我从twitter上检索数据。我在数据库中存储了一些ID,我正试图用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(Twittere)时,它会自动停止运行。我想继续下一个游标(下一个数据库的id)


共 (2) 个答案

  1. # 1 楼答案

    这是因为在循环中有try-catch块,所以当捕捉到异常时,它就会跳出循环

    将try catch block放置在内部,而block将解决问题

  2. # 2 楼答案

    如果要这样做,需要将try-catch块移动到while中。目前,一旦在while中抛出异常,它就会退出while并转到catch块,执行会在该块之后停止。如果将try移动到while内,while即使在抛出并处理异常后仍将继续

    循环和try-catch的结构应该是这样的

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