Arsalan Khattak
Arsalan Khattak

Reputation: 958

Looping in Handling Exception

I have made a simple program. I want to add loop for try, catch statement, so if the user write input, he gets and error message and the program let him to write again.

Console.WriteLine("Enter The File Location");
string userValue = Console.ReadLine();
try
{
    string content = File.ReadAllText(userValue);
    Console.WriteLine(content);            
}
catch (FileNotFoundException ex)
{
    Console.WriteLine("There was a Problem");
    Console.WriteLine(ex.Message);
}  
catch (DirectoryNotFoundException ex)
{
    Console.WriteLine("There was a Problem");
    Console.WriteLine("Could not find the Directory");
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

Console.ReadLine();

Upvotes: 0

Views: 283

Answers (4)

Ralf Bönning
Ralf Bönning

Reputation: 15485

You can wrap your code inside a while loop, that repeats the code until a successful operation has been completed.

var success = false;
while (success == false)
{
    Console.WriteLine("Enter The File Location");
    string userValue = Console.ReadLine();
    try
    {
        string content = File.ReadAllText(userValue);
        Console.WriteLine(content);            
        success = true;
    }
    catch (FileNotFoundException ex)
    {
        Console.WriteLine("There was a Problem");
        Console.WriteLine(ex.Message);
    }  
    catch (DirectoryNotFoundException ex)
    {
        Console.WriteLine("There was a Problem");
        Console.WriteLine("Could not find the Directory");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }    
}

Upvotes: 2

David Sette
David Sette

Reputation: 753

When you are able to check for invalid input, it's usually best to do that rather than let an exception happen. In your case you can check File.Exists(...) and/or Directory.Exists(...) based on the user's input. You could make those the conditions of your loop statement, so continue to prompt the user until they use a correct directory and file. However, I would suggest that this is not necessarily the best user experience, as you are expecting them to know a valid file and directory, which they may not. Certainly you should provide a way for them to exit out of the loop.

Upvotes: 1

Alberto
Alberto

Reputation: 69

You don't need loop. Yuo can use Recursive function. Try this: https://dotnetfiddle.net/4NR26P

Upvotes: 0

semvdwal
semvdwal

Reputation: 215

I would use a while construct with a specified condition when the user input is done (when you detect an Enter keypress, or have a complete command or otherwise). Then you can loop while that condition is not met (and there is no unrecoverable error), and use your code above to check for user errors and print messages when needed.

Upvotes: 0

Related Questions