【发布时间】:2013-03-11 12:31:23
【问题描述】:
我有一种方法可以检查数据库中记录的图像名称。如果有这种情况,我会尝试使用记录的路径加载图像。如果没有,我会加载默认图像。
首先,我将整个方法放在try-catch 块中,其中catch(Exception ex) 并且无论是什么异常,我刚刚返回Error loading image:
if (File.Exists(imgPath + "\\" + imageName))
{
try
{
using (var temp = new Bitmap(imgPath + "\\" + imageName))
{
pictureBox1.Image = new Bitmap(temp);
}
if (pictureBox1.Image.Width > defaultPicBoxWidth)
{
pictureBox1.Width = defaultPicBoxWidth;
}
}
catch (Exception ex)
{
logger.Error(ex.ToString());
MessageBox.Show("Error loading image!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
然后我发现有时我可能在数据库中有一条记录,但由于某种原因该文件可能丢失了,所以我添加了检查:
if (imageName != null && !File.Exists(imgPath + "\\" + imageName))
现在我也需要针对这种情况的适当消息。我得出的结论是,我可以 - 使用几个 try-catch 块来处理这些部分,或者抛出异常并处理调用方法的异常。
我选择了第二个选项,现在整个代码是:
if (imageName != null && !File.Exists(imgPath + "\\" + imageName))
{
throw new FileNotFoundException();
}
if (File.Exists(imgPath + "\\" + imageName))
{
//try
//{
using (var temp = new Bitmap(imgPath + "\\" + imageName))
{
pictureBox1.Image = new Bitmap(temp);
}
if (pictureBox1.Image.Width > defaultPicBoxWidth)
{
pictureBox1.Width = defaultPicBoxWidth;
}
//}
//catch (Exception ex)
//{
// logger.Error(ex.ToString());
// MessageBox.Show("Error loading image!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
//}
}
这就是我调用该方法的地方:
try
{
//The name of the method described above
LoadSavedOrDefaultImage(imageInfo, entity.Picture, txtCode.Text, imageLocation);
}
catch (FileNotFoundException ex)
{
logger.Error(ex.ToString());
MessageBox.Show("Error loading image! The file wasn't found.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
LogErrorAndShowMessage(ex, Resources.ERROR_LOAD);
}
我更喜欢这个,但我不能确切地说出为什么。一般的问题是 - 这是处理异常的正确方法。更具体的一个 - 在我的确切情况下,放置try-catch 块的更好地方是哪里?对我来说,在方法本身的主体中是有意义的,因为这样我就不需要在我为我调用该方法的任何地方编写那些 try-catch 块,它以这种方式更加封装。现在还有两个 try-catch 块,但是如果将来逻辑发生变化,我可能想抛出更多不同的异常,这是将异常处理保留在方法本身而不是在调用它的位置的另一个原因,但另一方面.. . 我想看看你的意见。
【问题讨论】:
标签: c# .net exception-handling error-handling filenotfoundexception