微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何处理try catch异常android

我正在使用方法getBitmap来显示图像.当我使用它作为方法时,如果它返回位图显示图像但是如果它返回null,则捕获异常.但是如果输入的url也是错误的,它应该处理FileNotFoundException.如何在UI中处理两个异常并显示
public Bitmap getBitmap(final String src) {

        try {
              InputStream stream = null;
              URL url = new URL(src);
         java.net.URL url = new java.net.URL(src);
              URLConnection connection = url.openConnection();

            InputStream input = connection.getInputStream();
            myBitmaps = BitmapFactory.decodeStream(input);    
           return myBitmaps;        
         } catch (IOException e) {
            e.printstacktrace(); 
            Log.e("IO","IO"+e);
            return null;
        } 
        catch(OutOfMemoryError e1) {
             e1.printstacktrace();  
             Log.e("Memory exceptions","exceptions"+e1);
             return null;
        }
        }

在活动中,我已经这样给了

Bitmap filename=service.getBitmap(url_Box.getText().toString());
    if(file_name!=null)
        {
          displaybitmap(file_name);
        } 
    else
       {  //Toast.makeText("Memory Error");
       //my question is how to handle two exception in UI where memory error and also 
      // when entered url is wrong,file not found exceptions also to handle.
        }

解决方法

我真的,真的不推荐这个……
try {
     ...
} catch (Exception e) {
     // This will catch any exception,because they are all descended from Exception
     System.out.println("Error " + e.getMessage());
     return null;
}

您是否正在查看堆栈跟踪以调试问题?跟踪它们应该不难.查看LogCat并查看大块红色文本以查看导致崩溃的方法以及您的错误.

如果您以这种方式捕获所有错误,您的程序将无法按预期运行,并且当您的用户报告时,您将无法从Android电子市场获得错误报告.

您可以使用UncaughtExceptionHandler来防止一些崩溃.我使用一个,但仅用于将堆栈跟踪打印到文件,因为我正在远离计算机的手机上调试应用程序.但是在我完成之后,我将未捕获的异常传递给认的Android UncaughtExceptionHandler,因为我希望Android能够正确处理它,并让用户有机会向我发送堆栈跟踪.

原文地址:https://www.jb51.cc/android/316801.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐