Android 如何处理异常并防止应用程序崩溃
我正在使用AmazonAWSSDK从S3下载图像。有时,当未找到映像时,会引发异常“AmazonS3Exception:状态代码:404”。然而,这似乎是一个例外,不应该使应用程序崩溃。如何处理此异常,使其不会使应用程序崩溃?抱歉,我是Java&Android的noob。要跟进type-a1pha的回答:Android 如何处理异常并防止应用程序崩溃,android,Android,我正在使用AmazonAWSSDK从S3下载图像。有时,当未找到映像时,会引发异常“AmazonS3Exception:状态代码:404”。然而,这似乎是一个例外,不应该使应用程序崩溃。如何处理此异常,使其不会使应用程序崩溃?抱歉,我是Java&Android的noob。要跟进type-a1pha的回答: try{ //code throwing exception } catch (AmazonS3Exception) {} 如果希望优雅地处理异常,可以使用try-catch语句。它
try{
//code throwing exception
} catch (AmazonS3Exception) {}
如果希望优雅地处理异常,可以使用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();
}
也许可以澄清异常处理,并表明您可以优雅地记录异常