Yrneh
Yrneh

Reputation: 63

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. 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#)

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();

Upvotes: 2

Views: 3292

Answers (4)

Simon Karlsson
Simon Karlsson

Reputation: 4129

You should read the file inside the try catch and catch FileNotFoundException, like this:

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
}

Upvotes: 3

Austin
Austin

Reputation: 904

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

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 ());

}

Upvotes: 0

JoJo
JoJo

Reputation: 806

Try catch just doesn't work like this. 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

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 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");
} 

Upvotes: 0

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

You need to put the code that is error prone inside of try block.

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.

Upvotes: 0

Related Questions