我有以下带有多个try ... catch的代码,有什么方法可以使其更简单?
try {
saveToInternalStorage(((BitmapDrawable) image1.getDrawable()).getBitmap(), imageFilename + "_1");
} catch (Exception e) {
e.printStackTrace();
}
try {
saveToInternalStorage(((BitmapDrawable) image2.getDrawable()).getBitmap(), imageFilename + "_2");
} catch (Exception e) {
e.printStackTrace();
}
try {
saveToInternalStorage(((BitmapDrawable) image3.getDrawable()).getBitmap(), imageFilename + "_3");
} catch (Exception e) {
e.printStackTrace();
}
try {
saveToInternalStorage(((BitmapDrawable) image4.getDrawable()).getBitmap(), imageFilename + "_4");
} catch (Exception e) {
e.printStackTrace();
}
答案 0 :(得分:2)
是的...但是评论中提出的担忧是有效的
所有这些。这是一堆代码
var array = new[]{ image1, image2, image3, image4 };
for (var i = 0; i < array.Length; i++)
{
try
{
saveToInternalStorage(array[i].getDrawable().getBitmap(), $"{imageFilename}_{i + 1}");
}
catch (Exception e)
{
e.printStackTrace();
}
}
答案 1 :(得分:1)
如果您写的确实是适当的逻辑,则:
private void trySave(Whatever image. String file) {
try {
saveToInternalStorage(image.getDrawable().getBitmap(), file);
}
catch (Exception exc) {
exc.printStackTrace();
}
}
并致电为
trySave(image1, imageFilename+"_1)";
trySave(image2, imageFilename+"_2");
trySave(image3, imageFilename+"_3");
trySave(image4, imageFilename+"_4");
子例程减少重复。
答案 2 :(得分:0)
如果要删除多个try catch,可以将try catch块放入saveToInternalStorage中,然后,如果您不关心错误,则只使用finally而不是catch。 由于它无法跟踪引发的错误,因此更快地被捕获。
// example 1 if you are not interested in the error or the success responce
void saveToInternalStorage(BitmapDrawable bd, String file_name)
{
try{
//..put your code here
}finally{
}
}
// example 2 if you are interested in just geting the success response
boolean saveToInternalStorage(BitmapDrawable bd, String file_name)
{
try{
//..put your code here
return true;
}finally{
return false;
}
}
// example 3 if you are don't want to touch your saveToInternalStorage function
boolean saveToInternalStorage(BitmapDrawable bd, String file_name)
{
try{
saveToInternalStorage(bd,file_name)
return true;
}finally{
return false;
}
}