Search code examples
delphidelphi-7

"JPEG Error #42" not catch by try...except when loading broken Image


I am trying to load a broken image with TImage.Picture.LoadFromFile() (the image file is 0kb in size) but try..except is not catching JPEG error #42:

try  
  Image1.Picture.LoadFromFile('myfile.jpg'); // myfile.jpg is broken image
except
  on e: exception do
    ShowMessage('Fail to load');
end;

Message show "JPEG error #42", not "Fail to load".

broken image sample


Solution

  • What's happening is that the error is being triggered asynchronously when the image control paints itself. The actual image data is not processed until then, and the image does not paint itself until the next paint cycle. Which happens after your event handler returns.

    If you want to be able to handle the error synchronously then you need to force the invalid image data to be processed immediately. Here is one rather ugly way to make that happen:

    try  
      Image1.Picture.LoadFromFile('myfile.jpg'); // myfile.jpg is broken image
      (Image1.Picture.Graphic as TJPEGImage).DIBNeeded;
    except
      on e:exception do
        ShowMessage('Fail to load');
    end;
    

    Note that modern versions of Delphi have addressed this issue and the code in your question will behave as you would hope and expect.