1

Let say my application code is structure is layer.

For eg
First Layer is client service layer.
Second is validation Layer
Third is custom Business Logic Layer. Forth is Core Business Logic Layer.
Fifth is ORM Layer.

We want that at any point/level of application code if we see that the request made by user cannot be provisioned (may be due to lack of data required or any other application logic constrain) And we want to throw error which should not be caught by any other layer except the top layer, so that the error msg can be shown to User properly.

To achieve this i was thinking to create a new class which extends Error. So that it remain unchecked and can skip any try catch block which catches Exception.

Does it looks like a good strategy , is there a bttern pattern as my solution goes against the javadoc ?

The Javadoc explains it well:

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.

enter image description here

Bhuvan
  • 4,028
  • 6
  • 42
  • 84

3 Answers3

2

No, this is bad strategy. In general you should almost never extend Error. Extend Exception (for checked exceptions) or RuntimeException (for unchecked exceptions). The idea of throwing the exception from the lower level to bypass the intermediate try-catch blocks is also very bad. Intermediate try-catch blocks are designed to catch and possibly rethrow the exceptions wrapping them in more business-oriented exception objects. If you are unsatisfied with the logic in the intermediate layers, then change that logic, do not try to hack it.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
  • "If you are unsatisfied with the logic in the intermediate layers, then change that logic, do not try to hack it." this will trigger a huge change in codebase as most try catch pattern catch(exception e)... – Bhuvan Jul 06 '15 at 12:08
  • @user2410148 See this answer for some ideas. http://stackoverflow.com/a/14722976/1168342 The pattern is known as "convert exceptions" http://c2.com/cgi/wiki?ConvertExceptions – Fuhrmanator Jul 07 '15 at 03:56
0

You can declare the methods in the lower layers to throw an exception instead of catching them:

public businessLayerFoo() throws Exception {
   ...
}

An Error is usually used to indicate a serious problem occurred during execution.

NightShade
  • 141
  • 1
  • 8
0

If you really don't want to make all your method throwing the same base Exception , you can make your exception extends RuntimeException it will not be checked.

You should never catch Error. You should never extends Error unless you want your program to stop immediately with a panic message.

pdem
  • 3,880
  • 1
  • 24
  • 38