文件夹中最长的文件路径 - 如何处理异常

时间:2017-01-23 17:28:10

标签: c# exception-handling try-catch

此函数应在其获取的路径中找到最长的文件作为参数 它似乎运作良好的问题是我不知道如何处理异常 在PathTooLongException的情况下,我想将_MaxPath设置为-2并退出该函数,如果将其他异常设置为-1并退出该函数,则将其设置为最长的文件路径。
我不确定在这种情况下处理异常的正确方法是什么。

可能是一个愚蠢的问题,但我是C#的新手......

static int _MaxPath = 0;
public static void GetLongestFilePath(string p)
{
    try
    {
        foreach (string d in Directory.GetDirectories(p))
        {
            foreach (string f in Directory.GetFiles(d))
            {
                if (f.Length > _MaxPath)
                {
                    _MaxPath = f.Length;
                }
            }
            GetLongestFilePath(d);
        }
    }
    catch (Exception e)
    {
        if (e is PathTooLongException)
        {
            _MaxPath = -1;
        }
    }
    finally
    {
        System.Environment.Exit(-99);
    }
}

2 个答案:

答案 0 :(得分:1)

您可以拥有多个具有多种异常类型的catch块:

    try
    {
       // ...
    }
    catch (PathTooLongException e)
    {
       _MaxPath = -2;
       return;
    }
    catch (Exception e) //anything else
    {
       _MaxPath = -1;
       // ...
    }
    finally 
    {
       // ...
    }

答案 1 :(得分:1)

您可以在自己的块中捕获特定的异常类型:

static int _MaxPath = 0;
public static void GetLongestFilePath(string p)
{
    try
    {
        foreach (string d in Directory.GetDirectories(p))
        {
            foreach (string f in Directory.GetFiles(d))
            {
                if (f.Length > _MaxPath)
                {
                    _MaxPath = f.Length;
                }
            }
            GetLongestFilePath(d);
        }
    }
    catch (PathTooLongException e)
    {
        _MaxPath = -2;
    }
    catch (Exception e)
    {
        _MaxPath = -1;
    }
    finally
    {
        System.Environment.Exit(-99);
    }
}