C# 用户代码未处理DirectoryNotFoundException

C# 用户代码未处理DirectoryNotFoundException,c#,asp.net,C#,Asp.net,我对try-catch和异常处理非常陌生。我希望我的程序在找不到目录或文件时捕获异常。 每当我运行该程序时,我都会收到错误“DirectoryNotFoundException未由用户代码处理-在something.dll中发生'System.IO.DirectoryNotFoundException'类型的异常,但未在用户代码中处理” 我可以看到Visual Studio在DirectoryNotFoundDirection中断,有什么想法吗 try { LiveDownloadOpe

我对try-catch和异常处理非常陌生。我希望我的程序在找不到目录或文件时捕获异常。 每当我运行该程序时,我都会收到错误“DirectoryNotFoundException未由用户代码处理-在something.dll中发生'System.IO.DirectoryNotFoundException'类型的异常,但未在用户代码中处理”

我可以看到Visual Studio在DirectoryNotFoundDirection中断,有什么想法吗

try {
    LiveDownloadOperation operation = await connectClient.CreateBackgroundDownloadAsync(filePath);
    var result = await operation.StartAsync();
}
catch (FileNotFoundException filEx) {
   Debug.WriteLine(filEx.Message);
   throw filEx;
}
catch (DirectoryNotFoundException dirEx) {
   Debug.WriteLine(dirEx.Message);
   throw;
}
catch (IOException ioEx) {
    Debug.WriteLine(ioEx.Message);
    throw ioEx;
}
catch (Exception ex) {
    Debug.WriteLine(ex.Message);
    throw;
}

编辑:由于目录不存在(或存在权限问题等),若要在目录中显示代码,请重试,它会引发DirectoryNotFoundException


您可以处理它,然后重新抛出--因为,调试器正确地说异常未被处理。

您可以在
try
块中显示代码吗?好的,您重新抛出它。这意味着,尽管您确实记录了异常,但异常仍会在调用堆栈中未经处理地向上移动。在
try
块中,您还可以首先检查目录是否存在。如果没有,您可以创建它,或者抛出异常或执行其他操作,具体取决于您的需要。