Search code examples
javaassertassertion

What JVM is doing internally when it encounters an assert statement in java program?


I am new to the assertions concept in java. Where ever i read about the assert concept in java, it is always saying like, if we use assert expression1:expression2, it will use the default constructor or one of the seven constructors in AssertionError class in case it fails. But what my doubt is Who is actually throwing this AssertionError error when the assert statement fails ? Will the compiler adds the "throw new AssertionError(---)" or the JVM will check for the expression and throw the AssertionError (like ArithmeticException, NullPointerException etc...) ?


Solution

  • The assertion proposal explains it:

    The assert statement [is] merely syntactic sugar for this if statement:

    if ($assertionsEnabled && !(Expression1))
        throw new AssertionError(Expression2);
    

    $assertionsEnabled is a synthetic boolean field that also gets added by the compiler.