如何捕捉在C#中的异常处理 [英] How to catch exceptions from processes in C#

查看:107
本文介绍了如何捕捉在C#中的异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这里有一个接受亚军的程序,看起来是这样的:

I have an acceptance runner program here that looks something like this:

public Result Run(CommandParser parser)
{
    var result = new Result();
    var watch = new Stopwatch();

    watch.Start();

    try
    {
        _testConsole.Start();

        parser.ForEachInput(input =>
        {
            _testConsole.StandardInput.WriteLine(input);
            return _testConsole.TotalProcessorTime.TotalSeconds < parser.TimeLimit;
        });

        if (TimeLimitExceeded(parser.TimeLimit))
        {
            watch.Stop();
            _testConsole.Kill();
            ReportThatTestTimedOut(result);
        }
        else
        {
            result.Status = GetProgramOutput() == parser.Expected ? ResultStatus.Passed : ResultStatus.Failed;
            watch.Stop();
        }
    }
    catch (Exception)
    {
        result.Status = ResultStatus.Exception;
    }

    result.Elapsed = watch.Elapsed;
    return result;
}



_testConsole是一个过程适配器,包装正规的.NET程序到更多的东西可行的。
我不过也很难赶上从启动过程中的任何异常(即catch语句是毫无意义的在这里)我使用类似

the _testConsole is an Process adapter that wraps a regular .net process into something more workable. I do however have a hard time to catch any exceptions from the started process (i.e. the catch statement is pointless here) I'm using something like:

_process = new Process
                           {
                               StartInfo =
                                   {
                                       FileName = pathToProcess,
                                       UseShellExecute = false,
                                       CreateNoWindow = true,
                                       RedirectStandardInput = true,
                                       RedirectStandardOutput = true,
                                       RedirectStandardError = true,
                                       Arguments = arguments
                                   }
                           };



建立过程。
任何想法?

to set up the process. Any ideas?

推荐答案

例外不流从一个进程到另一个。你能做的最好的是监测过程的退出代码 - 传统的退出代码0代表成功,任何其他退出代码表示的错误

Exceptions don't flow from one process to another. The best you could do would be to monitor the exit code of the process - conventionally, an exit code of 0 represents success, and any other exit code represents an error.

不管是为你推出进程的情况下,当然是另当别论。

Whether that's the case for the processes you're launching is a different matter, of course.

这篇关于如何捕捉在C#中的异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆