this 中的项目编号 6文章指出:
Try not to re-throw the exception because of the price. Bu if
re-throwing had been a must, re-throw the same exception instead of
creating a new exception. This will bring additional performance. You
may add additional info in each layer to that exception.
好吧,但这违反了层的分离,不是吗?
假设我有一个特定的 DAO 实现,它抛出一个 SQLException
假设我的服务层(或业务层..)从 DAO 层调用一个方法,但决定不处理抛出的异常。
如果我重新把SQLException抛给View层,我的View层就不会只耦合到DAO层了,不是吗?
抛出一个新的 Exception 是不是正确的,这样 View 就仅依赖于下面的第一层,而不是第二层?
除了性能之外,抛出相同的Exception有什么好处?
If I re-throw the SQLException
to the View Layer, my View Layer will not only be coupled to the DAO Layer, isn't it?
这是绝对正确的。
Isn't it right to throw a new Exception, so that View is dependent only on layer one level below, and not two?
当然。如果您的 DAO 层无法处理来自 SQL 的异常,它应该捕获它,尽可能多地理解它,然后抛出它自己的异常。
考虑一个例子:假设您的 DAO 层允许您添加新项目,其中某个属性必须是唯一的。 SQL 层可能具有唯一约束或唯一索引以在 RDBMS 层上强制执行此约束。如果 DAO 层的调用者试图保存一个违反唯一性约束的对象,将抛出 SQL 异常。如果您让此异常传播给调用者,他们很可能不知道如何处理它,甚至可能将其显示给最终用户:
ORA-00001: unique constraint (UxPatient_rec_soc) violated
这个解决方案非常糟糕,但尝试在客户端理解它的替代方案更加脆弱。
你的 DAO 应该捕获异常,决定它对调用者意味着什么,然后抛出它自己的异常。这样您就可以独立于调用者更改实现。
一般注意事项:在决定抛出/重新抛出异常时,性能考虑应该是最不重要的,因为只有在极少数异常情况下才会抛出异常。界面的清晰度更为重要。