What is the preferred Throwable to use in a private utility class constructor?

前端 未结 8 1259
青春惊慌失措
青春惊慌失措 2020-12-14 01:07

Effective Java (Second Edition), Item 4, discusses using private constructors to enforce noninstantiability. Here\'s the code sample from the book:

public fi         


        
相关标签:
8条回答
  • 2020-12-14 01:26

    No no no, with all due respect to Josh Bloch, never throw an AssertionError unless it's from an assertion. If you want an AssertionError here, throw it with assert(false). Then someone reading the code can find it later.

    Even better, define your own exception, say CantInstantiateUtilityClass. then you'll have code that says

    try {
        // some stuff
    } catch (CantInstantiateUtilityClass e) {
        // react
    }
    

    so that the reader of the catcher knows what happened.


    Let me just note that the standard still defines AssertionError as the result of a failed assertion, not as what some beginner thinks ought to be thrown in place of a well-defined informative exception. Sadly, good exception discipline is perhaps the least encouraged skill in Java programming.

    0 讨论(0)
  • 2020-12-14 01:33

    UnsupportedOperationException sounds like the best fit, though a checked exception would be even better, since it might warn someone erroneously instantiating the class at compile time.

    0 讨论(0)
提交回复
热议问题