gpt4 book ai didi

C# 预先捕获异常或验证参数

转载 作者:行者123 更新时间:2023-11-30 14:50:18 26 4
gpt4 key购买 nike

这是一个关于异常处理和预防的问题。

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

  1. 现在,您会建议像我一样捕获它,还是会在调用 Path.Combine 之前真正检查无效字符?
  2. 关于可以适用于大多数情况的一般性建议呢?
  3. 也许有一篇关于此的 Microsoft 文章?

Path.Combine 文档:
https://msdn.microsoft.com/de-de/library/fyy7a5kt(v=vs.110).aspx

.NET 引用源:
http://referencesource.microsoft.com/#mscorlib/system/io/path.cs,2d7263f86a526264

Microsoft 性能提示(请参阅抛出更少的异常一章):
https://msdn.microsoft.com/en-us/library/ms973839.aspx

最佳答案

  1. 捕获异常很慢,因为异常抛出会堆栈跟踪
  2. 捕获异常的可读性较差;这是一种臭名昭著的 goto:如果发生了什么事,然后 goto catch

这就是我投票支持验证的原因:

   if (path1 == null) 
return null;
if (path2 == null)
return null;

//TODO: put other validations here, e.g. Path.GetInvalidFileNameChars()

return System.IO.Path.Combine(path1, path2);

并且仅针对异常(exception) 情况捕获异常:

   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) {
...
}

关于C# 预先捕获异常或验证参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36931591/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com