C#尝试捕捉并返回提示
我有一个try-catch块,当它捕获到异常时,我希望它返回到ReadLine(),以便用户可以再次尝试输入有效的选择C#尝试捕捉并返回提示,c#,error-handling,console,try-catch,C#,Error Handling,Console,Try Catch,我有一个try-catch块,当它捕获到异常时,我希望它返回到ReadLine(),以便用户可以再次尝试输入有效的选择 Console.Write("CSV File: "); string csvFile = Console.ReadLine(); try { List<DictionaryLabels> values = csvRead(csvFile); } catch (System.IO.FileNotFoundException) {
Console.Write("CSV File: ");
string csvFile = Console.ReadLine();
try
{
List<DictionaryLabels> values = csvRead(csvFile);
}
catch (System.IO.FileNotFoundException)
{
Console.WriteLine("CSV File not found \nPress any key to contiune");
Console.ReadLine();
}
Console.Write(“CSV文件:”);
字符串csvFile=Console.ReadLine();
尝试
{
列表值=csvRead(csvFile);
}
捕获(System.IO.FileNotFoundException)
{
Console.WriteLine(“未找到CSV文件\n按任意键继续”);
Console.ReadLine();
}
您在尝试结束时将valid设置为true,并从catch中删除readline(感谢Quantic指出我的遗漏)。您的问题解决方案可能有效,但它不符合编程的概念。每当出现意外情况时,应使用Try-catch块,而不是“可能发生”的场景 下面的代码中描述了处理此问题的一种方法:如果文件存在,您将从用户处获得第一个输入&验证。确认后,您可以尝试打开它。如果失败(例如,文件不包含CSV格式的文本),则应引发异常 如果它在
中的条件while(condition)
不会为false(!File.Exists()),循环将一次又一次地运行
using System.IO;
Console.Write("Please enter the path for file:");
string lPath = Console.ReadLine();
while(!File.Exists(lPath))
{
Console.Write("File has not been found. Please enter new path:");
lPath = Console.ReadLine();
}
try
{
List<DictionaryLabels> values = csvRead(lPath);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
使用System.IO;
编写(“请输入文件的路径:”);
字符串lPath=Console.ReadLine();
而(!File.Exists(lPath))
{
Write(“未找到文件。请输入新路径:”);
lPath=Console.ReadLine();
}
尝试
{
列表值=csvRead(lPath);
}
捕获(例外e)
{
控制台写入线(e.Message);
}
查找而循环您误用了try-catch概念。您应该做的是检查文件是否存在,然后将其解析为“值”;文件总是可以在文件.Exists(csvFile)
和后续的文件.Read(csvFile)
@Quantic之间消失或锁定。你说得对。我习惯于处理固定文件。感谢您的更正。然后卸下Console.ReadLine()代码>在捕捉内。如果你展示了一个正确的实现,就会更清晰。我不想展示整个实现,因为它看起来像是一个家庭作业,所以我只想在正确的方向上做一点小动作。
using System.IO;
Console.Write("Please enter the path for file:");
string lPath = Console.ReadLine();
while(!File.Exists(lPath))
{
Console.Write("File has not been found. Please enter new path:");
lPath = Console.ReadLine();
}
try
{
List<DictionaryLabels> values = csvRead(lPath);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.Write("CSV full path File: ");
string csvFile = Console.ReadLine();
while (!ValidateCsv(csvFile))
{
Console.Write("Retype full path CSV File: ");
csvFile = Console.ReadLine();
}
private static bool ValidateCsv(string csvFile)
{
bool isPathTrue = false;
FileInfo csvFileInfo = new FileInfo(csvFile);
isPathTrue = csvFileInfo.Exists;
return isPathTrue;
}