【问题标题】:What is wrong with this Exception Handling in JavaJava中的这个异常处理有什么问题
【发布时间】:2013-04-20 11:19:53
【问题描述】:

下面是完整的方法。它以字符串形式返回给定 URL 的 HTML 代码。 经过某些测试后,我得出的结论是 try 块被跳过了。但我不知道为什么。

    public static String getHtml(String url)
 {
     StringBuilder result = new StringBuilder();
     try {
         HttpClient httpClient = new DefaultHttpClient();
         HttpContext localContext = new BasicHttpContext();
         HttpGet httpGet = new HttpGet(url);
         HttpResponse response = httpClient.execute(httpGet, localContext);


         BufferedReader reader = new BufferedReader(
             new InputStreamReader(
               response.getEntity().getContent()
             )
           );

         String line = null;
         char c = '"'; //The Java complains about this type of char So I removed it from the source.
         while ((line = reader.readLine()) != null){
           for(int i = line.length()-1; i >0; --i){
               if (line.charAt(i) != c){
                   result.append(line);
               }
           }
         }
         return result.toString();
     } catch(Exception e){
            result.append("<p><img src=http://desperateshadows.files.wordpress.com/2013/02/img_0721.jpg?w=730 class=size-full alt=Green green not evergreen /></p><p>Little flower at a glance</p>"); //A test Source

         return result.toString();
     }



 }

【问题讨论】:

  • 第一:不要“吃掉”异常。在返回结果之前调用e.printStacktrace();。第二:从 logcat 发布堆栈跟踪。你的AndroidManifest.xml也加了上网权限吗?
  • 你的日志猫显示什么。????
  • 你怎么知道它被跳过了?
  • 是的,我有 Inernet 权限。
  • 问题是你没有在你的catch块中放置足够的调试输出。 Log.e(TAG, "getHtml() caught an exception", e); 保持你的理智。

标签: java android exception


【解决方案1】:

您正在从 UI 线程调用 execute()。自 Android 3.0+ 起,不允许在 UI 线程上运行阻塞操作。

【讨论】:

    【解决方案2】:

    在 android manifest.xml 中放上网权限

    <manifest xlmns:android...> ...
        <application android:label="@string/app_name" >...
        </application>    
        <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    </manifest>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-30
      • 1970-01-01
      • 2017-12-08
      • 2016-02-16
      • 2016-07-14
      • 2014-10-26
      • 1970-01-01
      • 2011-02-03
      相关资源
      最近更新 更多