If a Java package throws a checked exception of its dependency module

I have a Java project that is divided into 3 modules. These three modules are a separate Maven project, but there is a dependency between them. The connection is simple:

Module A depends on module B

Module B depends on module C

  • Module C is a library that handles low-level database tasks such as creating a session, etc.
  • Module B is a database library that defines DAO, DTO, entities, etc.
  • Module A is a Restful Web Service that contains business logic and uses the B library to access the database.

I have a checked exception defined in module C which is thrown by a public method. Module B may receive this exception.

My question is whether this is good practice for B

  • Catch this thrown exception and throw another checked exception defined locally in module B into module A.
  • Do not catch the checked exception, but declare this exception in your public method so that it is passed to module A.

My personal opinion is that a module should only throw a checked exception, which it defines to its client modules, if only it is a predefined Java exception. But there is, of course, the flip side to this, which means that I have to create two different exceptions in several modules in order to represent the same error condition.

Can anyone share their opinions?

+4
source share
2 answers

I would be less worried about throwing exceptions and more about handling them.

Exceptions must be exceptional. They should only be caught when they are handled properly. If you cannot handle it, do nothing if it is an uncontrolled exception or catch and throw it if it is.

Some modules should never throw exceptions. I think of user interface controllers because the user has a bad experience if they see a stack trace. I also think about web services because HTTP does not know or care about your exceptions.

Your error handling strategy should not revolve around exceptions. You can send codes between modules and have a contract for their processing.

Record is not processed.

I could not advise you what to do, based on what you published. I would like to know more about what modules do.

+2
source

I look at this in terms of the type of connection. If module B completely encapsulates the types in module C from module A, then definitely do not enter a type relationship between A and C just for the exception. If module B already provides CA types (that is, A directly depends on C, and also through its dependence on B), then go ahead and throw C. exceptions.

+2
source

Source: https://habr.com/ru/post/1500030/


All Articles