C#提前捕获异常或验证参数
这是一个关于异常处理和预防的问题C#提前捕获异常或验证参数,c#,performance,exception,C#,Performance,Exception,这是一个关于异常处理和预防的问题 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); } c
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;
}
}
由于异常对性能的影响很大,我们应该尽量减少抛出异常的机会。在下面的示例中,我排除了Path.Combine
可能引发ArgumentnullException
的可能性。这很容易做到,几乎不会以任何方式影响性能。但是,如果两个参数字符串中的一个包含由GetInvalidPathChars
提供的任何无效字符,则Path.Combine
也会抛出ArgumentException
Path.Combine
之前检查无效字符李>
路径。合并
文档:.NET参考源:
Microsoft性能提示(请参阅“抛出较少异常”一章):
try {
// I can't validate this, since just after I've finished it and ready to read
// someone can
// - delete/rename the file
// - change permissions
// - lock file (e.g. start writing to it)
String data = File.ReadAllText(@"C:\MyData.txt");
...
}
catch (IOException e) {
...
}
正如这个术语所说,异常是用来处理意外情况的。我投票赞成事先用代码处理可预见的情况 异常会影响性能 如果是API
public static string PathCombineNoEx(string path1, string path2)
{
if (String.IsNullOrWhiteSpace(path1))
{
throw new ArgumentnullException(path1);
}
//Same goes for Path2
return System.IO.Path.Combine(path1, path2);
}
否则,德米特里的回答就行了
有帮助的SO帖子:
作为旁注,IsNullOrWhiteSpace返回bool,您的代码将根据bool进行检查null@Noël Widmer:是的,我没有捕捉到路径的
参数异常。组合:相反,我建议验证:检查路径Path.GetInvalidFileNameChars()
,Path.GetInvalidPathChars()
和其他(如果需要)我知道如何操作。我只是想知道你是否还在验证它。谢谢:)
public static string PathCombineNoEx(string path1, string path2)
{
if (String.IsNullOrWhiteSpace(path1))
{
throw new ArgumentnullException(path1);
}
//Same goes for Path2
return System.IO.Path.Combine(path1, path2);
}