我遇到了以下代码片段。名称已更改以保护无辜者:
public void RunProgram()
{
System.IO.FileInfo fInfo = new System.IO.FileInfo(Application.StartupPath + "Program.exe");
if (!fInfo.Exists)
{
System.Windows.Forms.MessageBox.Show("Program could not be found, please verify your installation.\n\nDetails:\n" + fInfo.FullName);
return;
}
try
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo pStart = new System.Diagnostics.ProcessStartInfo();
pStart.FileName = fInfo.FullName;
pStart.UseShellExecute = true;
process.StartInfo = pStart;
process.Start();
}
catch
{
System.Windows.Forms.MessageBox.Show(string.Format("An error occurred trying to run the program:{0}", fInfo.FullName));
}
}
我知道这里有一些问题:
- 异常类型没有单独处理
- 错误消息信息不足
请放心,我也会解决这些问题,但我的主要问题是在 try/catch 块之前检查文件是否存在。这让我觉得有点多余。
异常处理的重点是捕捉意外情况。我完全希望文件在那里,因此删除存在检查并让异常处理捕获它,如果它对我来说不是一个合理的解决方案。
你怎么看?