简体   繁体   中英

Longest file path in a folder - how to handle exceptions

This function should find the longest file in a path it get as parameter.
It seems to work well the problem is I'm not sure how to handle exceptions.
In case of PathTooLongException I want to set _MaxPath to -2 and exit the function, in case of other exception set it to -1 and exit the function else set it to longest file path.
I'm not sure what is the right way to handle exceptions in that case.

Probably a dumb question but I'm new with 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);
    }
}

You can have multiple catch blocks with multiple Exception types:

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

You can catch the specific exception type in its own block:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM