【问题标题】:Longest file path in a folder - how to handle exceptions文件夹中最长的文件路径 - 如何处理异常
【发布时间】:2017-01-23 17:28:09
【问题描述】:

这个函数应该在它作为参数的路径中找到最长的文件。
它似乎运作良好,问题是我不确定如何处理异常。
在 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);
    }
}

【问题讨论】:

  • 为什么将结果存储在静态字段中?那不方便。还有一个名称以Get 开头的方法应该返回一些东西,它不应该是无效的。

标签: c# exception-handling try-catch


【解决方案1】:

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

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

【讨论】:

  • 谢谢,但是如果出现异常我应该如何退出函数呢?如果我在 finally 中使用 System.Environment.Exit(-99) 并调试它,它不会进入 catch 语句。
  • 如果在catch块中使用return语句,会立即退出方法。你不需要它。删除 return 语句,它将运行 finally 块。
  • 我不明白为什么,但是当我有一个 finally 块时,它也不会进入 catch 块,如果我使用 return 它也不会完全退出函数,可能是因为它是递归的。
【解决方案2】:

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

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);
    }
}

【讨论】:

    猜你喜欢
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多