Sir Cringe
Sir Cringe

Reputation: 212

Catching BitmapFactory exceptions

I am simply trying to load a bitmap from a file using the BitmapFactory class as shown:

Bitmap b = BitmapFactory.decodeFile(getActivity().getFilesDir() + "/myImage.jpg");

This works fine except in instances where the file does not exist on filesystem and it throws a java.io.FileNotFoundException (No such file or directory). My question is, how do I catch this exception and keep going? I have surrounded the statement in a try block but the catch statement says it will never be reached for any FileNotFoundException. Taking a look at the BitmapFactory class shows that it doesn't throw any exceptions. What am I doing wrong here?

Upvotes: 2

Views: 645

Answers (2)

Neph
Neph

Reputation: 2001

This answer was tested with Java 11/Android 11 but might still apply to older or newer versions.

Unable to decode

stream: java.io.FileNotFoundException: /storage/emulated/0/Android/data/com.xyz.myapp/files/myimage.png: open

failed: ENOENT (No such file or directory)

"How do I catch this exception?"

You can't because it's not a real exception. The decodeFile function catches the actual exception, then prints it to console using Log.e (code copied from the BitmapFactory class):

catch (Exception e) {
    /*  do nothing.
        If the exception happened on open, bm will be null.
    */
    Log.e("BitmapFactory", "Unable to decode stream: " + e);
}

As the docs say:

Returns

Bitmap the resulting decoded bitmap, or null if it could not be decoded.

The only thing you can do is to check if the returned Bitmap is null and act accordingly if it is but there's not exception to be caught here.

Upvotes: 1

TmKVU
TmKVU

Reputation: 3000

Try to explicitly define the right Exception

try{
    Bitmap b = BitmapFactory.decodeFile(getActivity().getFilesDir() + "/myImage.jpg");
}catch(java.io.FileNotFoundException ex){
   //Caught exception
}

Upvotes: 0

Related Questions