How to avoid creating custom exception classes while still throwing exceptions at the appropriate level of abstraction?

I look at my understanding of exception handling (in the context of Java) and try to figure out which types of exceptions are most suitable for throwing. One comment I regularly see is that it’s usually better to avoid creating many custom exceptions - it’s better to use the “widely understood” standard exceptions and only “create a custom type of exception when you need to annotate the exception with additional information to help in programmatic treatment of the symptom. "

However, this seems somewhat opposite to the idea that you should "throw exceptions at the right level of abstraction." Looking at an example from Uncle Bob's Pure Code, the following examples are provided for the Employee class:

Bad: public TaxId getTaxId() throws EOFException
Good: public TaxId getTaxId() throws EmployeeDataNotAvailable

So, how do I combine these two “recommendations” - you should only throw exceptions at the right level of abstraction and rarely create your own exception classes. In addition, when searching for information on standard exceptions in Java, there is very little presented and formatted information about which standard exception classes are available - I am looking for standard exceptions that semantically still seem suitable for class calls, but do not find much to continue. Of course, you can find which exception classes are available in the jdk documentation, but just the lack of information and discussion on the Internet seems weird.

So, this is where I am now. Any suggestions and comments are greatly appreciated!

+4
source share
5

, . :

  • , , Exception , , RuntimeException. Javadocs , Exception, RuntimeException, , , , IOException.
  • Exception RuntimeException , , . , RuntimeException, try-catch. , Exception.

.

- -, . , , (, , , ..), 2 :

  • ElementNotFoundException, , , , . Customer#billingAddressLocation - null - - .
  • BillGenerationException, , .
+1

. AExeption BException, , , :

    } catch(AExeption ae) {
        // do something
    } catch(BException be) {
       // do something different
    }  

:

    } catch(AExeption ae | BException be ) {
        // do something
    }

, , , , .

+2

.

, .

:

, , "Connection Refused" "Connection timed out" , , , .

, , .

+1

. , , .

, getTaxiId , -, IOException . . , , .

+1

, . , , - , .

, EOFException - InvalidDataException, EmployeeDataException . , () , , , , . , , .

, - , .

, , - ! , AddressDataException, () , . , , DataException . , , , DataException, .

+1

All Articles