首页 > 解决方案 > 尽管 try-catch 出现异常错误并抛出异常尝试

问题描述

我很困惑,因为我在下面有这段代码,我相信它应该捕获异常:

    @SuppressWarnings("unchecked")
    public static String method(String userToken, int nthRecent) throws Exception
    {
      //my own user Token: 35a5b026870c49f69d3c688779ff26db
      String tweet = tweets.get(nthRecent);
      try
      {
         String urlString = "https://api.dandelion.eu/datatxt/sent/v1/?lang=en&text=";
         urlString += tweet;
         urlString = urlString + "&token="+userToken; 
         
         URL url = new URL(urlString);
         HttpURLConnection con = (HttpURLConnection) url.openConnection();
         con.setRequestMethod("GET");
         
         BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
         StringBuffer response = new StringBuffer();
         String line; 
         while ((line = in.readLine()) != null) 
         {
            response.append(line);
         }
         in.close();
         return response.toString();
         con.disconnect();
      }
      catch (Exception e)
      {
         e.printStackTrace();
         return null;
      }
   }

但我不断收到此错误消息:

TwitterPart3.java:42:错误:未报告的异常异常;必须被捕获或声明被抛出 consolePrint.println(bigBird.method(userToken, nthRecent));

我是否抛出了错误的异常?我已经尝试过 try-catch 和 throwing,所以我不确定为什么会这样。

更新:以下是我的主要方法:

   private static PrintStream consolePrint;
   public static void main(String[] args) throws TwitterException, IOException
   {
        consolePrint = System.out;
        SentimentAnalyser bigBird = new SentimentAnalyser(consolePrint);
        Scanner scan = new Scanner(System.in);
        consolePrint.print("Please enter a Twitter handle, do not include the @symbol --> ");
        String twitter_handle = scan.next();
        
        while(!twitter_handle.equals("done"))
        {
            bigBird.queryHandle(twitter_handle);
            consolePrint.print("Enter the \"nth\" most recent tweet you would like analysed from " + twitter_handle + "--> ");
            int nthRecent = scan.nextInt();
            consolePrint.print("Enter your user Token " + twitter_handle + "--> ");
            String userToken = scan.next(); 
            consolePrint.println(bigBird.method(userToken, nthRecent)); // this is the line 42 the error refers to
            twitter_handle = scan.next();
        }
   }

标签: javaexceptiontry-catchthrow

解决方案


推荐阅读