简体   繁体   中英

Try..Except ignored inside a thread

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?

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; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM