Home > Software design >  Try..Except ignored inside a thread
Try..Except ignored inside a thread

Time:12-07

I have a basic try..except to catch errors when trying to load a PNG file into a TImage:

try
  Previewimage.Picture.LoadFromFile(filename);
except
  //code to handle exception
end;

Normally this works fine if the file does not exist, or in my case the PNG is corrupted. I have no control over the source creation of the PNG, so need to catch when the PNG cannot be loaded, ie it gives the error:

This "Portable Network Graphics" image is not valid because it contains invalid pieces of data (crc error).

My issue is that the try..except is within a worker thread. This seems to cause the try..except to be ignored, and my program crashes with the CRC exception.

Are there any easy fixes for this issue?

CodePudding user response:

Exceptions and try..except blocks work just fine in worker threads. But accessing UI controls without proper synchronization can lead to all kinds of problems. So just don't do it.

In the context of the worker thread, load the PNG file using a local TPicture object, or better a TPNGImage object, then use TThread.Synchronize() or TThread.Notify() to Assign() that object to the TImage in the context of the main thread, eg:

try
  PNG := TPNGImage.Create;
  try
    PNG.LoadFromFile(filename);
    TThread.Synchronize(nil,
      procedure
      begin
        Previewimage.Picture.Assign(PNG);
      end
    );
  finally
    PNG.Free;
  end;
except
  //code to handle exception
end; 
  • Related