0
我正在使用Amazon AWS SDK從S3下載圖像。偶爾,當找不到圖像時,會拋出異常「AmazonS3Exception:Status Code:404」。但是,這似乎是一個例外,不應該使應用程序崩潰。我如何處理這個異常,以便它不會崩潰應用程序?道歉,我是Android的Java & noob。如何處理異常並防止崩潰應用程序
我正在使用Amazon AWS SDK從S3下載圖像。偶爾,當找不到圖像時,會拋出異常「AmazonS3Exception:Status Code:404」。但是,這似乎是一個例外,不應該使應用程序崩潰。我如何處理這個異常,以便它不會崩潰應用程序?道歉,我是Android的Java & noob。如何處理異常並防止崩潰應用程序
要跟進型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();
}
try{
//code throwing exception
} catch (AmazonS3Exception) {}
可能會澄清異常處理並顯示您可以優雅地記錄異常 – o0rebelious0o