使用泛型异常是明智的吗? [英] Is it wise to use generics for exceptions?
问题描述
我的团队正在清理我们使用 throws Exception
,并用特定的例外删除或替换它们。
My team is in the middle of cleaning up our use of throws Exception
and either removing or replacing them with specific exceptions.
常见的投票是因为未找到实体。我们应该为每个实体类扔一个通用的 NotFoundException
或特定的 SomeClassNotFoundException
A common throws is because an entity was not found. Should we be throwing a generic NotFoundException
or a specific SomeClassNotFoundException
for each entity class?
如果我们应该抛出一个特定的异常,我们应该为每个实体类型创建一个特定的Exception类?我们可以安全地使用仿制药吗?像这样 class NotFoundException< T extends EntityBaseClass>扩展Exception
然后构造函数负责声明我们处理的Entity类型?
If we should be throwing a specific exception, should we be creating a specific Exception class for each entity type? Can we safely use generics? Like this class NotFoundException<T extends EntityBaseClass> extends Exception
and then the constructor takes care of declaring what Entity type we're dealing with?
如果我们应该抛出一个特定的异常,这些异常是否扩展或实现一个 NotFoundException
抽象类或接口?
If we should be throwing a specific exception and not using generics, should those exceptions extend or implement a NotFoundException
abstract class or interface?
推荐答案
这个问题的简单的石蕊试验
A simple litmus test for the question
我们应该为每个实体类型创建一个特定的Exception类吗? >
Should we be creating a specific Exception class for each entity type?
是
有什么情况下我们会需要编写一个
catch
子句,它将捕获某些类X 而不是任何其他类抛出的未找到异常>
Are there any circumstances where we would need to write a
catch
clause that will catch a "not found" exception thrown by some class X and not by any other class?
如果答案是是,则单独的 ClassXNotFoundException
是有保证的;
If the answer is "yes", then a separate ClassXNotFoundException
is warranted; otherwise, it probably isn't.
至于您的问题的下半部分,该语言不允许使用异常类型的泛型。
As to the second half of your question, the language doesn't permit the use of generics for exception types.
这篇关于使用泛型异常是明智的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!