Android中如何处理try catch异常

14

我正在使用getBitmap方法显示图像。由于我将其作为方法使用,如果它返回位图,则显示图像,但如果它返回null,则捕获异常。但是,如果输入的网址不正确,它还应该处理FileNotFoundException。如何处理这两个异常并在用户界面上显示?

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

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

无法处理空指针异常。必须避免使用空实例。 - alicanbatur
5个回答

16

我非常、非常不建议这样做...

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能够正确处理它,并为用户提供发送堆栈跟踪的机会。


是的,@Jeba,你说得对。我也查找了uncaughtExceptionHandler,但不知道如何在服务和活动之间使用它。由于此方法位于服务中并且想要在活动中处理它。我的想法是不使用try catch。但我不知道如何使用它并进行处理。 - Shadow

3

检查你的捕获表达式

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

在这两个异常中,你返回了 null。我的建议是,在catch子句中初始化一个变量,然后在你的activity方法中检查该变量的值。

像这样:

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

现在在您的活动中:
 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

        }

        }

k..我会尝试并让你知道 @Brontok - Shadow

2

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


1
// try is nothing but a way to communicate a program 
  Example:

  try{ 
        //code here File IO operation like Files 
        // Code here Network Operation  
        //code here /0 (Divide by Zero )


     }catch (Exception e) {
        Log.e("Fail 2", e.toString());
         //At the level Exception Class handle the error in Exception Table 
         // Exception Create That Error  Object and throw it  
         //E.g: FileNotFoundException ,etc
        e.printStackTrace();
    }finally {
        //it always execute
    }

1
getBitmap方法中抛出异常,让客户端(Activity)处理异常,这样你就可以在获取位图或异常时跳过return null位图,并在catch块中进行相应的“默认位图加载”操作,以处理异常/错误情况(因为现在这是空值情况)。
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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接