问题描述
我已经在The Pragmatic Programmer和其他一些文章(包括来自Joel Spolsky的文章)中阅读过,你只应该在异常案例中抛出异常。否则,您应该返回一个错误。
I've read in The Pragmatic Programmer, and in some other articles (including one from Joel Spolsky), that you should only throw Exceptions in exceptional cases. Otherwise, you should return an error.
有时可能(返回 -1
, -0
,或正数
),但还有其他情况是不可能的。我的意思是,如果你返回一个类,你可以随时返回 null
,但我认为这个想法是返回一些会提醒调用者发生了什么事情。
Sometimes it is possible (returning -1
, -0
, or a positive number
, for example), but there are other cases where that is not possible. I mean, if you are returning a class, you can always return null
, but I think the idea is to return something that will alert the caller what happened.
如果我总是返回 null
,我认为这不是有用的:方法返回null,可能是因为A,B,C,D或E
If I always return null
, I don't think it is useful to say: If this method returns null, it could be because of A, B, C, D, or E
那么, C#?
编辑:
发布此问题后的几个小时,我在这里看到另一个问题这个问题本身就是发布的代码是一个很好的做法。
Hours after I posted this question, I saw another question here where the question itself was about wheter the code posted in was a good practice or not.
我看到这是另一种做我在这里问的方法。以下是链接:
I see that is another way of doing what I was asking here. Here is the link:
。此外,书也是值得阅读的例外资料。
By using numbers you're directly contradicting what Microsoft recommend with Exceptions. The best source of information I've found that de-mystifies the whole subject, is Jeffrey Richter's CLR via C# 3. Also the .NET Framework Guidelines book is worth a read for its material on Exceptions.
引用MSDN :
您可以采用的一个解决方案是 out
参数,得到结果。您的方法然后返回一个 bool
非常像您在框架中遇到的很多 TryParse
方法。
One solution you could adopt is an out
parameter, which gets the result. Your method then returns a bool
much like a lot TryParse
methods you meet in the framework.
这篇关于处理C#中的异常时的良好做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!