忽略错误并继续在C#中

时间:2013-03-23 15:02:18

标签: c# error-handling try-catch

我正在尝试在C#中打开3个程序,但是,如果发生错误,我仍然希望代码能够继续。换句话说,如果程序1出现故障,程序2和程序3仍应尝试打开。我也不想检查文件存在,因为程序需要一些开关,任何事情都可能失败。
如果程序1失败,下面的代码将弹出。如何忽略任何错误并仍然继续代码?

try
{
        string path = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
        //Program 1
        Process x = Process.Start("\"C:\\Program Files\\Company\\Office\\MyProgram1.EXE\"   /runtime  \"C:\\Program Files\\Company\\Config.xml\" /cmd RunServer");
        //Program 2
        Process x = Process.Start("\"C:\\Program Files\\Company\\Office\\MyProgram2.EXE\"   /runtime  \"C:\\Program Files\\Company\\Config.xml\" /cmd RunServer");
        //Program 3
        Process x = Process.Start("\"C:\\Program Files\\Company\\Office\\MyProgram3.EXE\"   /runtime  \"C:\\Program Files\\Company\\Config.xml\" /cmd RunServer");
}
catch {}

3 个答案:

答案 0 :(得分:10)

每个进程的单独Try...Catch可能是最好的方法。但是,如果您可以拥有任意数量的程序,则可以使用foreach循环,而不是为每次调用手动编写Try...Catch

List<Action> processesToCall = new List<Action>();  

string path = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
processesToCall.Add(() => Process.Start("\"C:\\Program Files\\Company\\Office\\MyProgram1.EXE\"   /runtime  \"C:\\Program Files\\Company\\Config.xml\" /cmd RunServer"));
processesToCall.Add(() => Process.Start("\"C:\\Program Files\\Company\\Office\\MyProgram2.EXE\"   /runtime  \"C:\\Program Files\\Company\\Config.xml\" /cmd RunServer") );
processesToCall.Add(() => Process.Start("\"C:\\Program Files\\Company\\Office\\MyProgram3.EXE\"   /runtime  \"C:\\Program Files\\Company\\Config.xml\" /cmd RunServer") );    

foreach(Action a in processesToCall)
{
    try
    {
       a();
    }
    catch
    {
       //log  (or whatever you want to do with it)
    }
}

这样您就不必为每个操作编写Try...Catch块,因此更容易添加更多操作。

答案 1 :(得分:3)

使用3个不同的try-catch

string path = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
try {        
    //Program 1
    Process x = Process.Start(path + "/runtime  \"C:\\Program Files\\Company\\Config.xml\" /cmd RunServer");
}
catch {}
try {
    //Program 2
    Process x = Process.Start(path + " /runtime  \"C:\\Program Files\\Company\\Config.xml\" /cmd RunServer");
catch {}
try  {
    //Program 3
    Process x = Process.Start(path + " /runtime  \"C:\\Program Files\\Company\\Config.xml\" /cmd RunServer");
catch {}

答案 2 :(得分:0)

你想忽略错误似乎很奇怪。无论如何,您可以将每个进程启动到try catch块中:

try{
   Process.Start(...);     
}catch(Exception e){
   //log error, if you want
}