Try/catch函数只运行一次,即使使用while循环C#也是如此



我正在尝试创建一个命令行应用程序,该应用程序搜索用户输入的歌曲名称和专辑目录,然后播放该歌曲。当用户输入一个不存在的歌曲名称或专辑时,程序会抛出一个DriectoryNotFoundException

我把";歌曲抓取器";函数,然后如果用户输入了无效目录,它会转到catch块并重试。它按预期工作,但只有一次。我试着放一个while循环,以确保try/catch函数一直工作,直到程序完全成功。

while (true)
{
try
{
MusicSelector.SongGrabber();
break;
}
catch (System.IO.DirectoryNotFoundException)
{
Console.WriteLine("Enter the exact song names and album.");
MusicSelector.SongGrabber();
}
}

我应该怎么做才能重试,直到用户输入一个有效的目录?

如果用户第二次出错,catch块中对MusicSelector.SongGrabber()的调用将抛出另一个未捕获的异常并结束程序。

所以不要再调用catch块中的MusicSelector.SongGrabber()。在catch块中不执行任何操作,或者最好打印一条消息来通知用户出现了什么问题。循环将再次迭代,并且MusicSelector.SongGrabber()的调用将在try块中再次完成,以便catch块可以在抛出新异常时捕获新异常。

当然,在之前给用户提供说明会很好,这样他们就知道应该做什么。也就是说,你可能还想考虑移动Console.WriteLine()

while (true)
{
try
{
Console.WriteLine("Enter the exact song names and album.");
MusicSelector.SongGrabber();
break;
}
catch (System.IO.DirectoryNotFoundException)
{
Console.WriteLine("The directory wasn't found.");
}
}

并且try-catch不是一个函数而是一个语句。

在成功调用SongGrabber后,break退出循环。从catch中删除break和调用(因为try块中有一个,循环将确保您重新访问它(,您应该是OK的:

while (true)
{
try
{
MusicSelector.SongGrabber();
// break removed here
}
catch (System.IO.DirectoryNotFoundException)
{
Console.WriteLine("Enter the exact song names and album.");
}
} 

如果我正在阅读您的描述,我会发现您正试图用变通方法(try-catch(来解决问题,而不是实际解决问题。

你知道用户可能填写了不正确的路径,所以你需要检查一下,然后如果正确就开始搜索,或者停止代码,并向用户反馈路径不正确。

我不太确定你是如何构建代码的,但下面是我的做法

Console.WriteLine("Enter the exact song names and album.");
var path = path.Trim(); //This is the parameter of the user sending the path
//If directory does not exist, don't even try. Give feedback and stop
if (!Directory.Exists(path))  
{  
//In case they cannot start it again then call the method on how to ask the path in here
Console.WriteLine("Path is invalid, try again");
return;
}
//try to get the song
var song = MusicSelector.SongGrabber(); //I assume you should pass the path here as a parameter.
//No song was found
if(song == null)
{
Console.WriteLine("There was no song found");
return;
}
//Song was found. Do something with it like play the song :)
MusicPlayer.Play(song);


最新更新