异常vs“if”在C# [英] Exceptions vs "if" in C#
本文介绍了异常vs“if”在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
bool
方法返回 false
如果有错误。例如: public bool Foo(string path,string fileName,ref string error)
{
if (path == null)
{
error =path is null;
返回false;
}
path + = fileName;
返回true;
}
正如你所看到的那样丑陋。我想使用这样的例外:
public voidFoo(string path,string fileName,ref string error)
{
if(path == null)
{
throw new SomeException(Path is null。);
}
path + = fileName;
返回true;
}
但是我们担心开销。我们应该吗?
解决方案
如果异常是不是抛出,那么你的 try ... catch
是可忽略的。所以,经验法则是:
- 如果异常可能被抛出(即,如果
path == null
是一个支持的场景),使用返回值。 - 如果异常是 em>,即如果
path == null
通常只有在开发人员使用你的函数时才会发生错误,然后使用异常。
I have a control flow question. In my company we create a lot of bool
methods that return false
if there was an error. Example:
public bool Foo(string path, string fileName, ref string error)
{
if (path == null)
{
error = "path is null";
return false;
}
path += fileName;
return true;
}
As you can see it's ugly. I want to use it with exceptions like so:
public voidFoo(string path, string fileName, ref string error)
{
if (path == null)
{
throw new SomeException("Path is null.");
}
path += fileName;
return true;
}
But we worry about the overhead. Should we?
解决方案
If the exception is not thrown, then the overhead of your try...catch
is negligable. So, the rule of thumb is:
- If the exception is likely to be thrown (i.e., if
path == null
is a "supported" scenario), use the return value. - If the exception is unlikely, i.e., if
path == null
usually only happens if the developer using your function makes a mistake, then use an exception.
这篇关于异常vs“if”在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文