What is an AssertionError? In which case should I throw it from my own code?

后端 未结 5 1562

In Item 2 of the \"Effective Java, 2nd edition\" book, there is this snippet of code, in which the author wants to forbid the empty initialization of an object.



        
5条回答
  •  情歌与酒
    2020-12-12 20:03

    I'm really late to party here, but most of the answers seem to be about the whys and whens of using assertions in general, rather than using AssertionError in particular.

    assert and throw new AssertionError() are very similar and serve the same conceptual purpose, but there are differences.

    1. throw new AssertionError() will throw the exception regardless of whether assertions are enabled for the jvm (i.e., through the -ea switch).
    2. The compiler knows that throw new AssertionError() will exit the block, so using it will let you avoid certain compiler errors that assert will not.

    For example:

        {
            boolean b = true;
            final int n;
            if ( b ) {
                n = 5;
            } else {
                throw new AssertionError();
            }
            System.out.println("n = " + n);
        }
    
        {
            boolean b = true;
            final int n;
            if ( b ) {
                n = 5;
            } else {
                assert false;
            }
            System.out.println("n = " + n);
        }
    

    The first block, above, compiles just fine. The second block does not compile, because the compiler cannot guarantee that n has been initialized by the time the code tries to print it out.

提交回复
热议问题