Java Programming - Assertions - Discussion


Which of the following statements is true?

[A]. In an assert statement, the expression after the colon ( : ) can be any Java expression.
[B]. If a switch block has no default, adding an assert default is considered appropriate.
[C]. In an assert statement, if the expression after the colon ( : ) does not have a value, the assert's error message will be empty.
[D]. It is appropriate to handle assertion failures using a catch clause.

Answer: Option B


Adding an assertion statement to a switch statement that previously had no default case is considered an excellent use of the assert mechanism.

Option A is incorrect because only Java expressions that return a value can be used. For instance, a method that returns void is illegal.

Option C is incorrect because the expression after the colon must have a value.

Option D is incorrect because assertions throw errors and not exceptions, and assertion errors do cause program termination and should not be handled.

Himani said: (Mar 29, 2011)  
Please tell me the meaning of assert in java.

Jirka said: (Apr 16, 2011)  
According to the official Java tutorial every expression returns a value, therefore option A is correct. If option A shall be incorrect, it shall use the term "statement" instead of expression.

An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value.

Daniil said: (Mar 1, 2015)  
About D:

You can fine process an error in try/catch clause.

Just write "catch (Error e)" or "catch (Throwable e)" but not "catch (Exception e)".

Ford Prefect said: (Jul 23, 2016)  
What Jirka said. A is a correct answer to this because Java does not support void expressions.

Achu said: (Jul 17, 2021)  
It is incorrect because the expression after the colon must have a value. Can anyone show an example?

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.