如何处理try catch异常android

Sha*_*dow 9 android exception-handling bitmap filenotfoundexception out-of-memory

我正在使用方法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;
        }
        }
Run Code Online (Sandbox Code Playgroud)

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

    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.
        }          
Run Code Online (Sandbox Code Playgroud)

Jeb*_*han 8

我真的,真的不推荐这个......

try {
     ...
} catch (Exception e) {
     // This will catch any exception, because they are all descended from Exception
     System.out.println("Error " + e.getMessage());
     return null;
}
Run Code Online (Sandbox Code Playgroud)

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

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

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


use*_*944 2

从您的资源中返回默认位图。但是有一个非常好的处理位图的库,称为 Universal Image Loader,请查看它。