【问题标题】:Exceptions not catching using catch block. Why?使用 catch 块未捕获的异常。为什么?
【发布时间】: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)这两种情况之一将导致(尝试/捕获)。干杯,伙计们。

标签: c# exception try-catch


【解决方案1】:

为了进行正确的 try/catch,您需要执行以下操作:

  1. 将您的方法放在try 块中
  2. catchException(s)
  3. throwException

这是一些代码

try
{
    app.MoveFolder(input1, input2);
}
// catch ArgumentException
catch(ArgumentException ex)
{
    throw;
}
// catch all others
catch(Exception ex)
{
    throw;
}

【讨论】:

  • 这样,Stacktrace 和可能的内部异常就会丢失。如果您打算在下一个级别抛出异常,只需使用 throw 而不创建新异常
  • 啊哈!出于某种原因,我决定将函数放在 catch 块之外,因为我认为它必须首先运行该函数,以便在它到达 try 或 catch 之前出现异常。这很好地回答了我的问题,非常感谢!
  • @jamessct 很高兴为您提供帮助。
  • 如果要重新抛出异常,最好使用throw; 保留堆栈跟踪。
【解决方案2】:

为了捕获函数抛出的异常,需要在 Try {} 中调用该函数。您可以像其他人所说的那样在 Try Block 中调用 MoveFolder。如果您在 Try 块之外抛出异常,它有时会被其他 catch 块拾取,或者只是未处理并产生错误。

try {
    app.MoveFolder(Something1, Something2);
} catch (ArgumentException ex) {
    //Do something with Exception
}

【讨论】:

  • 当他第一个到达那里时,我选择了另一个答案,但很高兴这回答了我的问题:)
猜你喜欢
  • 1970-01-01
  • 2021-05-13
  • 1970-01-01
  • 2010-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-11
  • 1970-01-01
相关资源
最近更新 更多