[英]How do I intercept an exception thrown by ImageMagick in C++?
我正在嘗試使用ImageMagick從互聯網上檢索照片。 偶爾會有一個問題。 我該如何處理?
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 */
例如,該特定URL的訪問受到限制。 ImageMagick只是拋出一個異常並說:
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
我以為我的try / catch可以捕獲到這一點,但是我從python獲得try / except的更多經驗。 我希望其他事情也可能導致故障,例如404或500。
我能做什么?
您正在嘗試捕獲一個int
,這不是ImageMagick引發的。 錯誤消息中指示了實際的異常類: Magick::ErrorCoder
。
您可以捕獲此異常類型:
try {
image.read(file);
}
catch(Magick::ErrorCoder& err) {
//...
};
或查閱ImageMagick文檔並獲取該文檔的基類。
通常,您至少應注意std :: exception。 任何明智的庫都將從std :: exception派生其異常類-這就是它的作用。
std :: exception的what()方法將向您提示有關異常的含義。 搜尋Magick :: ErrorCoder會產生Doxygen文檔,該文檔確實顯示它是從std :: exception派生的: http : //www.imagemagick.org/api/Magick++/classMagick_1_1ErrorCoder.html
正如syam所建議的那樣,因為您知道發生錯誤時會發出Magick :: ErrorCoder異常,所以您應該捕獲那些異常以及可能派生自其的中間異常類,但始終要捕獲std :: exception,因為這將使您的程序能夠報告庫拋出的任何明智的c ++異常。
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.