Exceptions and Abstractions

When should you throw a custom exception?

eg. I have a code that connects to a server. The code that connects to the server throws an IOException when it cannot connect. In the context of the method he called, this is fine. It is also great for network code.

But since this means the absence of a connection (and therefore not working), the exception extends up to ui. At this point, an IOException is very ambiguous. Something like NoConnectionException would be better.

So my question is: At what stage should you catch the exception, instead throw another (custom) exception that is better suited for abstraction?

+3
source share
5 answers

I would expect exceptions to be discussed in terms of what I asked for a create method. eg.

read -> ReadException
connect -> ConnectException
buildPortfolio -> FailedToBuildPortfolioException

etc .. This abstracts what happens under the covers (i.e. you connect via sockets, etc.). Typically, when I create an interface for a component, I often create the corresponding exception or set of exceptions. My interface will be called Component, and my exceptions are usually ComponentException(like RateSourceand RateSourceException). It is harmonized and easily exported to various projects as a complete set of components.

, , , , . , ( ) .

- (, , ) , ( ) , .

+4

, "-", , . ++, , . ++ . , . - catch() Java # .

, ++ - , . .

+1

, : a) . ) .

a) : - , , . : , ConnectionWhatEverException.

. - , ServiceOutOfOrderException. : , , - ConnectionException ( , ..). , , ConnectionException. , , .

b) . , Java. IllegalState IllegalArgument. , . , ServiceFailedException. - . 100 , ( , , ). , .

c) , java . , . , .

+1

, NoConnectionException, -? , , IO ?

0

?

. () .

. , (IOException). , , , ?

II. , .. , (?) .

, . - ( ).

III. I, II

NOTE. In addition, your customers should be able to tune in to the exact level of information that they are interested in, or rather, they should be able to tune everything that they are not interested in. Therefore, it's nice to get your custom exceptions from an IOException.

0
source

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


All Articles