简体   繁体   English

创建自定义例外的最佳做法是什么?

[英]What is the best practice for creating Custom Exceptions?

创建自定义异常时,最好的做法是为每个自定义异常创建一个单独的类文件,或者将自定义异常附加到它们所关联的类文件的末尾,或者创建一个文件(例如CustomExceptions.cs)并在那里添加自定义例外?

One class per file is always a good rule. 每个文件一个类总是一个好规则。

The other basics: 其他基础知识:

  • Mark your exception as [Serializable] 将您的例外标记为[Serializable]
  • Overload all the System.Exception constructors 重载所有System.Exception构造函数
  • Don't inherit from System.ApplicationException 不要从System.ApplicationException继承

Well ... I would say that you should follow the rule of one class per file, except in case if this exception is just for "internal" functionality in your class. 好吧...我想说的是,您应该遵循每个文件一个类的规则,除非这种例外仅适用于您类中的“内部”功能。 Then you can make it declared inside the class. 然后,您可以在类中声明它。 However, if exposed by any means to outside world, separate it from the class. 但是,如果以任何方式暴露给外界,请将其与班级分开。 This exposure could also be seen from the actual probability that this exception goes unhanded to the users of your class. 也可以从该异常未交付给班级用户的实际概率中看出这种情况。 In this case, I would also expose it and would not declare it inside. 在这种情况下,我还将公开它,并且不会在内部声明它。

As others have stated, one class per file rule is ideal. 正如其他人所说,每个文件规则一个类是理想的。 Another way to think of it, if you have a large application consisting of many modules, you will have multiple namespaces and it's important to keep the exceptions that a certain class method (or set of classes/methods) can throw within their respective namespaces. 另一种思考的方式是,如果您有一个包含许多模块的大型应用程序,那么您将拥有多个名称空间,并且重要的是要保留某些类方法(或一组类/方法)可以在其各自的名称空间中抛出的异常。 This makes the code more readable and the reasoning behind your custom exceptions easier to decipher for other developers ... Or for you in 6 months when you forgot why you made half of them :) 这使得代码更具可读性,并且对于其他开发人员来说,更容易解读您的自定义异常背后的原因……或者对于您在6个月内忘记了为什么只制作一半的原因而言:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 OData例外最佳实践 - Best Practice in OData for exceptions 在XML Web Services中,将异常传递回客户端的最佳做法是什么? - In XML Web Services, what is the best practice for passing exceptions back to the client? 捕获所有异常或特定异常的断路器的最佳实践是什么? - What is the best practice for a Circuit Breaker, catch all Exceptions or specific ones? 在自定义控件上实现 AutoSize 的最佳做法是什么? - What is the best practice for implementing AutoSize on custom controls? 检查DTO中的异常 - 最佳实践 - Checking for exceptions in DTO - best practice 如果父对象是单例,则创建dbcontext(EF核心)的最佳实践是什么? - What is the best practice for creating dbcontext (EF core) if the parent object is a singleton? 在C#中实现自定义异常的行业标准最佳实践是什么? - What are industry standard best practices for implementing custom exceptions in C#? 在实用程序类中引发异常的最佳实践 - Best practice for throwing exceptions in an utility class 最佳实践:创建脚本编辑器 - Best practice: creating a script editor 创建用户ID列表的最佳实践 - Best practice for creating a list of userIDs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM