Should Exceptions be placed in a separate package?

你。 提交于 2019-12-05 08:54:33

问题


I am taking on a project where all the Exceptions have been placed in a separate package com.myco.myproj.exceptions.

Is this good practice?


回答1:


I would expect the exceptions for a package to exist within that package. e.g.

com.oopsconsultancy.models.pricing

would contain pricing models and related exceptions. Anything else seems a bit counter-intuitive.




回答2:


It is a bad practice.

It is a coincidental grouping. Packages should be coherent. Don't group exceptions, interfaces, enum, abstract classes, etc., into their own package. Group related concepts instead.




回答3:


It would be a bad practice and will lead to unnecessary inter package dependencies. A custom exception class should always be defined in the same package as the classes which are capable of throwing it. You should try to minimize creating custom exception which are used all over the application, for that use Exception. Custom exception, as the name implies is a customized one, and should be focused on a specific section. This should be the same for custom utility classes.

Package should be able to present a single unit of functionality. Refer this for an example. A Custom Exception, which is gonna thrown out of it, is a part of that unit of functionality, and should be in the same package.

ex:

// Below should be in a single package
interface Draggable{}
abstract class Graphic{}
class Circle extends Graphic implements Draggable{}
class Box extends Graphic implements Draggable{}
final class GraphicValidator {// utility  class}
// don't put below in a separate 'exceptions' package, 
// who's gonna use it anyway other than the components in this package ?
class GraphicRenderingException extends Exception{}


来源:https://stackoverflow.com/questions/825281/should-exceptions-be-placed-in-a-separate-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!