简体   繁体   中英

How do I intercept an exception thrown by ImageMagick in C++?

I am trying to retrieve photos from the internet with ImageMagick. Once in a while there will be one with problems. How do I handle that?

char file[] = "http://distilleryimage10.s3.amazonaws.com/1f6be58e383e11e3acaf22000ae80c8d_8.jpg";

Magick::Image image;
// use Magick to load the file
try {
  image.read(file);
}
catch(int err) {
  printf("Error retrieving snapshot. Skipping.\n");
  return;
}
/* ... use this image */

That particular URL, for example has restricted access. ImageMagick just throws an exception and says:

terminate called after throwing an instance of 'Magick::ErrorCoder'
  what():  Magick: no data returned `http://distilleryimage10.s3.amazonaws.com/1f6be58e383e11e3acaf22000ae80c8d_8.jpg' @ error/url.c/ReadURLImage/232
Aborted

I thought my try/catch would capture that, but I have more experience with try/except from python. I would expect other things could cause faults, too, such as 404's or 500's.

What can I do?

You are trying to catch an int , which is not what ImageMagick throws. The actual exception class is indicated in your error message: Magick::ErrorCoder .

You could either catch this very exception type:

try {
  image.read(file);
}
catch(Magick::ErrorCoder& err) {
  //...
};

or consult the ImageMagick documentation and catch a base class of this one.

In general you should catch by std::exception at a minimum. Any sensible library will derive its exception classes from std::exception - that's what it's for.

The what() method of std::exception will give you some hint as to what the exception is about. Googling for Magick::ErrorCoder yields the Doxygen documentation which indeed shows it's derived from std::exception: http://www.imagemagick.org/api/Magick++/classMagick_1_1ErrorCoder.html

As syam suggests, since you know that Magick::ErrorCoder exceptions are emitted when things go wrong than you should catch those and possibly the intermediate exception classes from which it derives, but always catch std::exception as that will allow your program to report any sensible c++ exception thrown by your library.

try 
{
    image.read(file);
}
catch(Magick::ErrorCoder const & err) 
{
    // Some specific error handling for this problem
}
catch(Magick::Error const & err) 
{
    // Some general handling for ImageMagick errors
}
catch(Magick::Exception const & err) 
{
    // Some general handling for ImageMagick errors/warnings (apparently)
}
catch(std::exception const & err) 
{
    // Something bad happened - possibly caused by imagemagick using its libraries
    // incorrectly. Just report it - at least we didn't bomb out:
    std::cout << err.what();
}

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