【发布时间】:2014-10-18 06:37:14
【问题描述】:
我对 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;
}
编辑:在 try 中显示代码
【问题讨论】:
-
你能在
try块中显示代码吗? -
好吧,你重新扔它。这意味着尽管您确实记录了它,但异常仍然存在于未处理的调用堆栈中。
-
在您的
try块中,您也可以先检查目录是否存在。如果没有,您可以创建它,或者抛出异常或执行其他操作,具体取决于您的需要。