异常没有捕获使用catch块。为什么?

时间:2017-02-14 16:28:27

标签: c# exception try-catch

所以我在第一个学习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("pls wrk");
        }
        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: pls wrk

这不是我想要的,因为我希望catch块也能处理这个特定的ArgumentException。这与catch块有什么关系,我认为我指的是一个特定的参数异常?我原以为它会引用所有ArgumentExceptions。

我该如何解决这个问题?

感谢。

2 个答案:

答案 0 :(得分:3)

为了进行正确的尝试/捕获,您需要执行以下操作:

  1. 将您的方法放在try
  2. catch Exception(s)
  3. throw Exception
  4. 这是一些代码

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

答案 1 :(得分:0)

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

try 
{ 
   app.MoveFolder(Something1, Something2); 

} catch {ArgumentException) {

//Do something with Exception
}