处理C#中的异常时的良好做法 [英] Good practices when handling Exceptions in C#

查看:82
本文介绍了处理C#中的异常时的良好做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在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:

一般财产不足? a>

Generic property disadvantages?

推荐答案

通过使用数字,您直接与Microsoft推荐的例外相矛盾。我发现,最重要的信息来源是对整个主题的迷惑, Jeffrey Richter的CLR通过C# 3 。此外, .NET Framework准则书也是值得阅读的例外资料。

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#中的异常时的良好做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆