This is a question about exception handling and prevention.
public static string PathCombineNoEx(string path1, string path2)
{
if (path1 == null || path2 == null /*Either validate here*/)
{
return null;
}
try
{
return System.IO.Path.Combine(path1, path2);
}
catch (ArgumentException /*or catch here*/)
{
return null;
}
}
Since exceptions are an enormous hit on performance we should try to minimize the chance for exceptions to be thrown. In the following example I've eliminated the chance that Path.Combine
could throw an ArgumentnullException
. This was very easy to do and does almost not affect performance in any way. However, Path.Combine
also throws an ArgumentException
if one of the two parameter strings contains any invalid character provided by GetInvalidPathChars
.
- Now, would you recommend to catch this as I did or would you really check for invalid chars before calling the
Path.Combine
? - What about a general recommendation that can be applied to most situations.
- Maybe there is a Microsoft article about that?
Path.Combine
documentation:
https://msdn.microsoft.com/de-de/library/fyy7a5kt(v=vs.110).aspx
The .NET Reference Source:
http://referencesource.microsoft.com/#mscorlib/system/io/path.cs,2d7263f86a526264
Microsft performance tip (see chapter Throw fewer exceptions):
https://msdn.microsoft.com/en-us/library/ms973839.aspx