如何处理imageView.setImageURI的try-catch子句(Uri.parse(local_path));

Ale*_*dro 1 android try-catch filenotfoundexception imageview

我想在imageView尝试从用户先前删除的本地文件打开图像并显示默认图像时处理这种情况.为此,我尝试:

int flag = 0;
try{
        img_car.setImageURI(Uri.parse(path_picture));
        flag = 1;
    }
catch(Exception e){ //if I put FileNotFoundException I get error: Unreachable catch block for FileNotFoundException. This exception is never thrown from the try 
// statement body
        Log.i("TAG EXCEPTION PIC", e.getMessage());
        img_car.setImageResource(pictureId);
    }
Run Code Online (Sandbox Code Playgroud)

两者img_car.setImageResource(pictureId);img_car.setImageURI(Uri.parse(path_picture));(当图片物理存在时)工作.

我的问题是我无法捕获异常(当图片不存在时),基本上这个子句不会抛出它.(我LogCat不显示任何信息日志消息).即便如此,LogCat显示java.io.FileNotFoundException:

 09-06 13:12:22.066: W/ImageView(27274): Unable to open content:
 file:///storage/sdcard0/folder_name/my_image.PNG
 09-06 13:12:22.066: W/ImageView(27274): java.io.FileNotFoundException:
 /storage/sdcard0/folder_name/my_image.PNG: open
 failed: ENOENT (No such file or directory) 09-06 13:12:22.066:
 W/ImageView(27274):    at libcore.io.IoBridge.open(IoBridge.java:416)
 09-06 13:12:22.066: W/ImageView(27274):    at
 java.io.FileInputStream.<init>(FileInputStream.java:78) 09-06
 13:12:22.066: W/ImageView(27274):  at
 java.io.FileInputStream.<init>(FileInputStream.java:105) 09-06
 13:12:22.066: W/ImageView(27274):  at
 android.content.ContentResolver.openInputStream(ContentResolver.java:445)
 09-06 13:12:22.066: W/ImageView(27274):    at
 android.widget.ImageView.resolveUri(ImageView.java:631) 09-06
 13:12:22.066: W/ImageView(27274):  at
 android.widget.ImageView.setImageURI(ImageView.java:379) 09-06
 13:12:22.066: W/ImageView(27274):  at
 com.myapp....
Run Code Online (Sandbox Code Playgroud)

我指着这条线:img_car.setImageURI.另一个奇怪的事情是,标志1try-catch执行之后具有值,即使在上面的行上出现异常,所以理论上不应该执行该行.(对吗?).任何帮助将受到高度赞赏.谢谢!

Ale*_*dro 6

我退出了using try-catch,而是做了这个:

 Bitmap bitmap = BitmapFactory.decodeFile(path_picture);
            if(bitmap != null)
                imgdata.setImageBitmap(bitmap);
            else{
                imgdata.setImageDrawable(getResources().getDrawable(R.drawable.default_image));
            }
Run Code Online (Sandbox Code Playgroud)

我首先将内容提取到位图中,如果位图为null,则加载默认图像.有用.