gpt4 book ai didi

c# - C#中异常层次结构的良好实践

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

现在我在 PHP 之后编写 C# 代码。

在 PHP 中,我根据 Zend Framework 的建议创建了一个异常层次结构(Symfony 现在使用类似的东西)。

在包(例如 Order)中,我在这个文件夹中创建文件夹 Exception(从 php 转换为 C#):

namespace Order.Exception
{
interface ExceptionInterface{}
class ApplicationException : System.ApplicationException, ExceptionInterface{}
class OrderNotFoundException : ApplicationException {}
class SomethingHappensException : ApplicationException{}
}

我需要很多异常(相对)来方便地表达域中的东西。

是否有创建异常层次结构的良好做法?

我完全理解创作的技术细节。良好实践问题。

最佳答案

CLR via C#, 4th Edition 中的两句话:

If you want to define an exception type hierarchy, it is highlyrecommended that the hierarchy be shallow and wide in order to createas few base classes as possible. The reason is that base classes actas a way of treating lots of errors as one error, and this is usuallydangerous.

(...)

There are versioning ramifications here, too. If you define a newexception type derived from an existing exception type, then all codethat catches the existing base type will now catch your new type aswell. In some scenarios, this may be desired and in some scenarios,it may not be desired. The problem is that it really depends on howcode that catches the base class responds to the exception type andtypes derived from it. Code that never anticipated the new exceptionmay now behave unpredictably and open security holes. The persondefining the new exception type can’t know about all the places wherethe base exception is caught and how it is handled. And so, inpractice, it is impossible to make a good intelligent decision here.

关于c# - C#中异常层次结构的良好实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32912937/

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