我的代码看起来像这样,因为检查某些数据是否为图像的唯一可靠方法是实际尝试像图像一样加载它。
static void DownloadCompleted(HttpConnection conn) {
Image img;
HtmlDocument doc;
try {
img = Image.FromStream(conn.Stream);
} catch {
try {
doc = new HtmlDocument();
doc.Load(conn.Stream);
} catch { return; }
ProcessDocument(doc);
return;
}
ProcessImage(img);
return;
}
这看起来很糟糕!
处理这些情况的好方法是什么?你基本上被迫使用像 if
语句这样的异常?
最佳答案
你的逻辑结构是
if( /* Loading Image Fails */ )
/* Try Loading HTML */
所以我会尝试让代码以这种方式阅读。引入辅助方法可能是最干净的(尽管公认的冗长烦人):
bool LoadImage()
{
Image img;
try
{
img = Image.FromStream(conn.Stream);
}
catch( NotAnImageException /* or whatever it is */ )
{
return false;
}
ProcessImage(img);
return true;
}
bool LoadDocument()
{
// etc
}
所以你可以写
if( !LoadImage() )
LoadDocument();
或将其扩展为:
if( !LoadImage() && !LoadDocument() )
{
/* Complain */
}
关于c# - 捕获预期异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1990242/