简体   繁体   English

C#尝试捕捉

[英]C# try and catch

I've just signed up to the website so I have probably put this wrong. 我刚刚注册了网站,所以我可能把这个错了。 Anyways, I am trying to use the try and catch in C# to catch my file if it not found. 无论如何,我正在尝试使用C#中的try和catch来捕获我的文件(如果找不到)。 Here is my code for it at the moment. 这是我目前的代码。 To repeat myself, I want the program to read the file in, as it does- but then if the file is not found, I would like it to give an error saying "cannot find the file" or something along those lines, not simply just crash. 再说一遍,我希望程序像读取文件一样读取文件,但是如果找不到该文件,我希望它给出一个错误,提示“找不到文件”或类似的内容,而不仅仅是只是崩溃。 (I've just started learning C#) (我刚刚开始学习C#)

Thanks for the help! 谢谢您的帮助!

string file = @"C:\Users\Henry\Desktop\Assessments\Programming and data structures\grades_multiple.txt";
try
{
    file = @"C:\Users\Henry\Desktop\Assessments\Programming and data structures\grades_multiple.txt";
}
catch
{
    Console.WriteLine("Could not find the file - grades_multiple.txt");
}            
//ARRAY for string lines
string[] Line = new string[6];
Line[0] = File.ReadLines(file).Skip(1).Take(1).First();

You should read the file inside the try catch and catch FileNotFoundException , like this: 您应该在try catch和catch FileNotFoundException内部读取文件,如下所示:

var file = @"C:\Users\Henry\Desktop\Assessments\Programming and data structures\grades_multiple.txt";
string[] lines;
try
{
    lines = File.ReadAllLines(file);
}
catch (FileNotFoundException exnotfound)
{
    // file not found exception
}
catch (Exception ex)
{
    // handle other exceptions
}

You need to put the code that is error prone inside of try block. 您需要将容易出错的代码放在try块中。

try
{
    Line[0] = File.ReadLines(file).Skip(1).Take(1).First();
}
catch(Exception ex)
{
     Console.WriteLine("Could not find the file - grades_multiple.txt");
}   

BTW, you can handle this situation by checking if file exists first using File.Exists method.There is no need to catch exception for that. 顺便说一句,您可以通过使用File.Exists方法检查文件是否首先存在来处理这种情况。不需要catch异常。

Try catch just doesn't work like this. 尝试catch不能像这样工作。 You are trying to catch a line of code that changes a string and doesn't change a file, so the file doesn't need to exist, so it will never throw an exception (in your case), and it will never catch it. 您试图捕获一行更改字符串且不更改文件的代码,因此该文件不需要存在,因此它永远不会引发异常(在您的情况下),也永远不会捕获它。

You should surround code that can go wrong: File.ReadLines 您应该包围可能出错的代码: File.ReadLines

Your code will become like this: 您的代码将如下所示:

string file = @"C:\Users\Henry\Desktop\Assessments\Programming and data structures\grades_multiple.txt";

//can go wrong   
try
{ 
     //ARRAY for string lines
     string[] Line = new string[6];
     Line[0] = File.ReadLines(file).Skip(1).Take(1).First();
}
//File.ReadLines is null
catch
{
     Console.WriteLine("Could not find the file - grades_multiple.txt");
} 

I also think it is even better practice to check it with an if statement, instead of catching it when it goes wrong: 我还认为,最好使用if语句检查它,而不是在出现错误时捕获它:

//if file exists
if(File.Exists(file)) 
{
    //ARRAY for string lines
    string[] Line = new string[6];
    Line[0] = File.ReadLines(file).Skip(1).Take(1).First();
}
//File does not exist
else
{
     Console.WriteLine("Could not find the file - grades_multiple.txt");
} 

When ever possible you should try to avoid throwing exceptions just to display a message to the user or for conditions that can be easily tested. 只要有可能,就应该避免引发异常,仅是向用户显示消息或针对易于测试的条件。 This is primarily a performance consideration as throwing an exception is expensive. 这主要是出于性能考虑,因为抛出异常的代价很高。 Additionally performance can be impacted by loading the entire file into memory unless you know that the file is relatively small.. 另外,将整个文件加载到内存中可能会影响性能,除非您知道文件相对较小。

Here is a quick and raw example on how you may test for the condition and handle it. 这是一个简短的原始示例,说明如何测试条件并处理该条件。

void Main()
{
    var filePath ="C:\\TEST.DAT";

    if(!File.Exists(filePath)){ DisplayFileNotFoundError(filePath); }

    try
    {           
        var lines = GetFileLines(filePath);
        if(lines == null) { DisplayFileNotFoundError(filePath);}

        // do work with lines;
    }
    catch (Exception ex)
    {
        DisplayFileReadException(ex);
    }

}

void DisplayErrorMessageToUser(string filePath)
{
    Console.WriteLine("The file does not exist");
}

void DisplayFileReadException(Exception ex){
    Console.WriteLine(ex.Message);
}

string[] GetFileLines(string filePath){

    if(!File.Exists(filePath)){ return null; }

    string[] lines;
    try
    {           
        lines = File.ReadLines(filePath);
        return lines;
    }
    catch (FileNotFoundException fnf){
        Trace.WriteLine(fnf.Message);
        return null;
    }
    catch (Exception ex)
    {
        Trace.WriteLine(ex.Message);
        throw ex;
    }
}

Performance Test, FileNotFoundException vs File.Exists 性能测试,FileNotFoundException与File.Exists

void Main()
{
    int max = 100000;
    long[] feSampling = new long[max];
    long[] exSampling = new long[max];

    String pathRoot ="C:\\MISSINGFILE.TXT";
    String path = null;

    Stopwatch sw = new Stopwatch();
    for (int i = 0; i < max; i++)
    {
        path = pathRoot + i.ToString();
        sw.Start();
        File.Exists(pathRoot);
        sw.Stop();
        feSampling[i] = sw.ElapsedTicks;

        sw.Reset();
    }

    StreamReader sr = null;
    sw.Reset();
    for (int i = 0; i < max; i++)
    {
        path = pathRoot + i.ToString();
        try
        {           
            sw.Start();
            sr = File.OpenText(path);
        }
        catch (FileNotFoundException)
        {
            sw.Stop();
            exSampling[i] = sw.ElapsedTicks;
            sw.Reset();

            if(sr != null) { sr.Dispose();}
        }
    }

    Console.WriteLine("Total Samplings Per Case: {0}", max);
    Console.WriteLine("File.Exists (Ticsk) - Min: {0}, Max: {1}, Mean: {2}", feSampling.Min(), feSampling.Max(), feSampling.Average ());
    Console.WriteLine("FileNotFoundException (Ticks) - Min: {0}, Max: {1}, Mean: {2}", exSampling.Min(), exSampling.Max(), exSampling.Average ());

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM