【发布时间】:2017-02-14 16:28:26
【问题描述】:
所以我在第一个学习 C# 的项目中使用了一些 try/catch 块。在大多数情况下,他们工作得很好。然而,有一些代码在异常点仍然会中断,尽管它正在找到我期待和希望的确切异常类型。我将提供一个发生此问题的代码示例。
这是我尝试捕获异常的地方:
app.MoveFolder(input1, input2);
try {
//code here
} catch (ArgumentException) {
//code here
}
break;
这是我创建异常的函数:
public void MoveFolder(string folderPath, string newLocation) {
this.ThrowExceptionIfFolderDoesntExist(folderPath);
if (Directory.Exists(newLocation) == true) {
throw new ArgumentException("example");
}
Directory.Move(folderPath, newLocation);
}
ThrowExceptionIfFolderDoesntExist() 函数导致:
private void ThrowExceptionIfFolderDoesntExist(string folderPath) {
if (this.CheckFolderExists(folderPath) == false) {
throw new ArgumentException("This folder does not exist");
}
}
所以,如您所见,我的 MoveFolder() 函数中的 this 和 if 语句都应该返回我希望捕获的 ArgumentExceptions。在后一种功能的情况下,这可以按预期工作。但是,如果我尝试将文件夹移动到已存在的位置,则会得到以下信息:
Unhandled Exception: System.ArgumentException: example
这不是我想要的,因为我希望 catch 块也能处理这个特殊的 ArgumentException。这与我指的是特定参数异常的 catch 块有关吗?我原以为它会引用所有 ArgumentExceptions。
我该如何解决这个问题?
【问题讨论】:
-
好吧,对 MoveFolder 的调用不在 try 块内,为什么您希望捕获异常?
-
抛出异常的东西 (MoveFolder) 存在于 try catch 块之外。在 try 块中移动 app.MoveFolder(input1, input2)
-
app.MoveFolder(input1, input2);必须在try... 您的第一个//code here评论所在的位置 -
现在感觉有点傻!我认为它会按照我的方式工作,因为我在考虑 1)运行方法 2)这两种情况之一将导致(尝试/捕获)。干杯,伙计们。