抛出异常时退出C#Console应用程序

时间:2014-12-28 15:58:18

标签: c#

我的代码从文件中读取文本。 我需要添加一个方法,如果文件不在正确的位置,程序将退出。

try {
    TextReader tr = new StreamReader("C:\\textfile.txt");

        for (int i = 0; i < 4; i++)
        {
            ListLines[i] = tr.ReadLine();
        }
    }
catch (Exception e)
    {
    Console.WriteLine("File not found - the app will now exit");
    }

是否可能,我应该使用哪些命令?

2 个答案:

答案 0 :(得分:6)

我想到了三个选择。

首先,您可以构建代码,以便在此时从Main方法返回。除非您已经运行其他(非后台)线程,否则应用程序将终止。

或者,您可以重新抛出异常,例如与throw; - 之后会将堆栈跟踪转储到控制台,这可能是也可能不是你想要的。

最后,您可以使用Environment.Exit来终止该过程。例如:

using System;

class Test
{
    public static void Main (string[] args)
    {
        Console.WriteLine("Before");
        Environment.Exit(1);
        Console.WriteLine("After");
    }
}

此处会打印Before,但After不会。

答案 1 :(得分:3)

您可以使用Environment.Exit(0);和Application.Exit

try {
    TextReader tr = new StreamReader("C:\\textfile.txt");

        for (int i = 0; i < 4; i++)
        {
            ListLines[i] = tr.ReadLine();
        }
    }
catch (Exception e)
    {
    Environment.Exit(0)
    }
相关问题