如何处理异常并防止崩溃的应用程序

时间:2013-07-25 19:18:22

标签: android

我正在使用Amazon AWS SDK从S3下载图像。有时,当找不到图像时,会抛出异常“AmazonS3Exception:Status Code:404”。但是,这似乎是一个例外,不应该崩溃应用程序。如何处理此异常以使其不会崩溃应用程序?抱歉,我是Java& amp;机器人。

2 个答案:

答案 0 :(得分:0)

try{
    //code throwing exception
} catch (AmazonS3Exception) {}

答案 1 :(得分:0)

跟进类型-a1pha的答案:

如果要优雅地处理异常,可以使用try-catch语句。它的工作原理如下:

try {
    // Here you put the code that may throw an exception
} catch (AmazonS3Exception e) {
    // Looks like we errored out, log the exception and
    // tell the user that we 404'd
    Log.e(TAG, "Error fetching file from Amazon S3", e);
    Toast.makeText(context, "Error 404 while fetching file: file not found", Toast.LENGTH_SHORT).show();
    // Insert any other code you need here to recover from the error
} finally {
    // Note that the finally part is optional but useful if you want
    // to do something after the try-catch statement is finished
    // for example, if you were using an inputStream:
    inputStream.close();
}