Catching image failure is not working (try/catch)

This doesnt work!

void setup() {
   try {
      image = loadImage("image.png");
   } catch (Exception e) {
      image = loadImage("error.png");
   }
}
1 Like

Hi @Aryszin,

I would recommend, before you’re posting things like this, to always consider to read the manuals, resp. references about. It clearly descibes on how to do error checking in several ways…

Cheers
— mnse

PS: to give a sneak preview… loadImage doesn’t throw exceptions… :wink:

3 Likes

void setup() {
image = loadImage(“image.png”);
if (image==null) {
image = loadImage(“error.png”);
}
}

1 Like

According to loadImage()'s reference, besides null, negative dimensions might also happen to indicate failure.

So if we need to be absolutely sure, we gotta check them as well, not just null:

PImage image;

void setup() {
  size(600, 600);
  noLoop();

  image = loadImage("image.png");

  if (!isValidImage(image))
    image = loadImage("https://CDN-Icons-png.FlatIcon.com/512/2731/2731804.png");

  println(image.width, image.height);
}

void draw() {
  background(0);
  set(width - image.width >> 1, height - image.height >> 1, image);
}

static final boolean isValidImage(final PImage img) {
  return img != null && img.width > 0 && img.height > 0;
}
4 Likes

im sorry i didnt really know that

1 Like