0

I have a function that checks if a path exist with parameter throwExceptionIfOffline which throws an exception if path doesn't exist because sometimes I want the calling function to exit right away (via try catch) if that is the case. Other times I want the calling function to keep going so I return false.

Is this a bad design decision and should I always return true or false and handle the exit logic in the calling function?

This is mostly to check if network drive is online.

public bool CheckPathValid(string fullFilePath, int maxTimeMillisecond, bool throwExceptionIfOffline)

some way im using this Exception:

try {
    CheckPathValid(@"\\somepath", 1000, true);
    //more code i want to skip....

} catch (Exception) {
    Log("func1 failed due to path not existing.");
}

return false:

try {
    foreach (path in somepathlist) {
       CheckPathValid(@"\\somepath", 1000, false); // fails go to next path
    }
} catch (Exception) {
    Log("func1 failed due to path not existing.");
}
Lightsout
  • 3,454
  • 2
  • 36
  • 65
  • @KenWhite Is a network drive offline considered exception if it should be on usually? Also this way helps me to not write extra if else statements which makes it cleaner imo, or should I be writing if else to handle offline in calling function – Lightsout Oct 14 '21 at 00:06
  • Not IMO, because it's a network drive. A local drive such as C: that really **is** always available would be an exception if it was not available. There's nothing exceptional about an occasional network outage (server maintenance, a temporary router issue, a DNS issue, etc. - none of those things are uncommon). Did you read the post I linked? – Ken White Oct 14 '21 at 00:09
  • @KenWhite I read like 3 sentences so I get the gist, btw what is your opinion on Nigel Bess's answer is that a good solution? – Lightsout Oct 14 '21 at 00:18
  • I'm not reviewing people's answers for you; that's not appropriate, and it's not appropriate for you to ask me to do so. – Ken White Oct 14 '21 at 00:19

1 Answers1

0

Yes this is a really bad design pattern.

The performance cost of throwing an exception is significant. Although structured exception handling is the recommended way of handling error conditions, make sure you use exceptions only in exceptional circumstances when error conditions occur. Do not use exceptions for regular control flow.

If you post an example of your calling code we can help you with an alternative solution.

Edit: Since you posted the calling code, here is how I would maintain the same functionality without throwing unnecessary exceptions:

void YourMethod()
{
    try 
    {
        if(!CheckPathValid(@"\\somepath", 1000))
        {
             Error();
             return;
        }
        //more code i want to skip....
    
    } 
    catch (Exception) 
    {
        Error();
    }
    void Error() => Log("func1 failed due to path not existing.");
}
Nigel
  • 2,961
  • 1
  • 14
  • 32