0

Why when an ArgumentException occurs because image.jpg has an invalid metadata header does the first example catch the exception, and the second example does not?

Example 1:

try
{
Uri myUri = new Uri("http://example.com/image.jpg", UriKind.RelativeOrAbsolute);
JpegBitmapDecoder decoder2 = new JpegBitmapDecoder(myUri,
                             BitmapCreateOptions.PreservePixelFormat,
                             BitmapCacheOption.Default);
BitmapSource bitmapSource2 = decoder2.Frames[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Example 2:

try
{
BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri("http://example.com/image.jpg");
src.EndInit();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
slugster
  • 49,403
  • 14
  • 95
  • 145
radicalpi
  • 907
  • 1
  • 9
  • 29

1 Answers1

0

It might be waiting until the image is requested to load it up, such as being set as the source for an Image control.

Perhaps it would give you an exception if you added

src.CacheOption = BitmapCacheOption.OnLoad;

to your declarations.

RandomEngy
  • 14,931
  • 5
  • 70
  • 113
  • I was setting the BitmapImage as the Background property on a border, but that was the first thing I checked. Even when I don't set the image as a source for something the exception still occurs. – radicalpi Apr 15 '11 at 22:36
  • To be clear, are you saying that both examples threw an exception, but that the exception was not caught in Example 2? – RandomEngy Apr 15 '11 at 23:02
  • Yes. Both threw an exception whenever there is a problem with the image being loaded, but the exception was not caught in example 2. – radicalpi Apr 15 '11 at 23:32
  • I am not aware of any exceptions other than OutOfMemoryException or ExecutionEngineException that can evade a general catch block like that. Are you sure it's being thrown from there? Maybe try putting a breakpoint in the catch block; maybe the message box isn't getting shown for some reason. – RandomEngy Apr 16 '11 at 17:54