How to handle try catch exception android

邮差的信 提交于 2020-01-12 07:16:46

问题


I am using a method getBitmap to display images. As I am using this as a method,if it returns bitmap display an image but if it returns null,catch an exception. But if url entered is wrong also, it should handle the FileNotFoundException. How to handle two exception and display in 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;
        }
        }

In Activity, i've given like this

    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.
        }          

回答1:


I really, really don't recommend this...

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

Are you looking at your stack traces to debug your issues? It should not be hard to track them down. Look at LogCat and review the big block of red text to see which method caused your crash and what your error was.

If you catch all your errors this way, your program is not going to behave as expected, and you will not get error reports from Android Market when your users report them.

You can use an UncaughtExceptionHandler to possibly prevent some crashes. I use one, but only to print stack traces to a file, for when I'm debugging an app on a phone away from my computer. But I pass on the uncaught exception to the default Android UncaughtExceptionHandler after I've done that, because I want Android to be able to handle it correctly, and give the user the opportunity to send me a stack trace.




回答2:


Return a default bitmap from your res. But there is a very good library for working with bitmap called Universal Image Loader, check it out.




回答3:


Check your catch expressions

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;
    }

Here you are returning null in both exceptions, My suggestion is initialize a variable in these catch clauses and in your activity method check the value of that variable.

Like this

 String exceptionName="";
 catch (IOException e) {
            e.printStackTrace(); 
            Log.e("IO","IO"+e);
            exceptionName="IOException";
            return null;

        } 
        catch(OutOfMemoryError e1) {
             e1.printStackTrace();  
             Log.e("Memory exceptions","exceptions"+e1);
             exceptionName="OutOfMemoryError";
             return null;
        }

Now in your activity

 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.

        if (exceptionName.equals("OutOfMemoryError")) {
            // Handle here  
        }
    else{
      // Handle here

        }

        }



回答4:


Throw the exceptions from the getBitmap method instead and let the client (Activity) handle the exceptions, in this case either you receive a Bitmap or an exception and can skip the return null bitmap and do the according "default bitmap loading" in the catch blocks, for the exception/error case instead (since this is the null case now).

public Bitmap getBitmap(final String src) throws FileNotFoundException,
        OutOfMemoryError, IOException, MalformedURLException {
    URL url = new URL(src);
    URLConnection connection = url.openConnection();
    InputStream input = connection.getInputStream();
    return BitmapFactory.decodeStream(input);
}


来源:https://stackoverflow.com/questions/22248311/how-to-handle-try-catch-exception-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!