如何处理try catch异常android

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22248311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:42:44  来源:igfitidea点击:

How to handle try catch exception android

androidexception-handlingbitmapout-of-memoryfilenotfoundexception

提问by Shadow

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?

我正在使用 getBitmap 方法来显示图像。当我使用它作为一种方法时,如果它返回位图显示图像但如果它返回空值,则捕获异常。但是如果输入的 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;
        }
        }

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

回答by Jebasuthan

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.

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

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.

如果您以这种方式捕获所有错误,您的程序将不会按预期运行,并且当您的用户报告错误时,您将不会从 Android Market 收到错误报告。

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.

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

回答by user3057944

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.

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

回答by Jitender Dev

Check your catch expressions

检查您的 catch 表达式

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 nullin both exceptions, My suggestion is initialize a variable in these catch clausesand in your activity method check the value of that variable.

在这里,您在两个异常中都返回null,我的建议是在这些 catch 子句中初始化一个变量,并在您的活动方法中检查该变量的值。

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

        }

        }

回答by Magnus

Throw the exceptions from the getBitmapmethod 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 nullbitmap and do the according "default bitmap loading" in the catch blocks, for the exception/error case instead (since this is the null case now).

getBitmap改为从方法中抛出异常并让客户端(活动)处理异常,在这种情况下,您可以收到位图或异常,并且可以跳过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);
}

回答by Ashif

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