How to handle try catch exception android

后端 未结 5 2034
滥情空心
滥情空心 2020-12-31 11:24

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 e

5条回答
  •  伪装坚强ぢ
    2020-12-31 12:11

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

提交回复
热议问题