本文介绍了编写自定义异常类时应考虑什么因素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自定义异常类什么时候最有价值?

是否应该或不应该使用这种情况?有什么好处?

When are custom Exception classes most-valuable?
Are there cases when they should or should not be used? What are the benefits?

相关问题:




  1. Performace Considerations for throwing Exceptions
  2. Do you write exceptions for specific issues or general exceptions?


推荐答案

要问自己的问题:



Questions to ask yourself:


  1. 谁将抓住它?如果没有人,那么你真的不需要一个自定义异常。

  2. 你会在哪里扔它?是否有足够的上下文容易获得,或者您需要捕获并重新抛出多次,然后异常对最终捕手有用吗?

  3. 你为什么扔它?由于您遇到异常并需要附加其他信息?因为在某些数据中遇到不可恢复的错误,需要将具体细节回传给客户端代码?因为你喜欢 throw ing something?

  4. 有什么例外?不是什么原因造成的,但是从捕获者的角度来看是什么?他们可以修复和重试?他们应该不要重试吗?他们应该通知用户吗?他们应该附加上下文信息然后重新抛出? 确定您需要传递的信息(如果有)...

  1. Who will be catching it? If no one, then you don't really need a custom exception.
  2. Where will you be throwing it? Is there enough context readily available, or will you need to catch and re-throw several times before the exception is useful to the final catcher?
  3. Why are you throwing it? Because you caught an exception and need to attach additional information? Because you encountered an unrecoverable error in some data, and need to communicate the specifics back to client code? Because you like throwing things?
  4. What is the exception? Not what caused it but what is it from the perspective of the catcher? Something they can fix and retry? Something they should never retry? Something they should notify the user about? Something they should attach context information to and then re-throw? What determines the information you'll need to pass along, if any...



戒律: / h3>

Precepts:


  1. 不要浪费时间,永远不会被抓住的自定义异常。

  2. 不要加倍异常:每个自定义异常类型应该有明确的情况,它可以并且应该被捕获;不匹配的异常应该分解成自己的自定义类型(而不是强制捕获者将条件逻辑建立到单个 catch()子句)中。

  3. 除非你有一个很好的原因,否则总是允许从先前捕获到的异常附加内部异常/数据。失去上下文很少有用。

  1. Do not waste time on custom exceptions that will never be caught.
  2. Do not "double up" exceptions: each custom exception type should have a well-defined case where it can and should be caught; exceptions that don't match should be broken out into their own custom types (rather than, say, forcing the catcher to build conditional logic into a single catch() clause).
  3. Unless you have a good reason not to, always allow attaching an inner exception / data from a previously-caught exception. Losing context is rarely helpful.

这篇关于编写自定义异常类时应考虑什么因素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 09:52