CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Exceptions

Exceptions handling
Assertions
Code assert statements

An assertion is a Java statement that enables you to assert an assumption about your program. An assertion contains a Boolean expression that should be true during program execution. Assertions can be used to assure program correctness and avoid logic errors.

How to work with assertions

  • You can use an assert statement to code an assertion, which is a condition that should be true at a given point in your application.
  • Assertions are disabled by default. To enable assertions:
    • From the command prompt: Enter the -ea switch after the java command for the application.
    • From TextPad: Choose Configure?Preferences, expand the Tools group, select the Run Java Application option, and add -ea at the beginning of the Parameters text box.
  • If assertions are enabled, the JRE evaluates assert statements and throws an AssertionError if the specified condition is false. If a message is coded in the assert statement, it's included in the AssertionError.

  • The AssertionError class has a no-arg constructor and seven overloaded single-argument constructors of type int, long, float, double, boolean, char, and Object. Since AssertionError is a subclass of Error, when an assertion becomes false, the program displays a message on the console and exits.
  • An assert statement shouldn't include any code that performs a task. If it does, the program will run differently depending on whether assertions are enabled or disabled.

The syntax of the assert statement

assert booleanExpression [: message ];

Code that makes a reasonable assertion about a calculation

for (int i = 1; i <= months; i++)
{
    futureValue =
        (futureValue + monthlyInvestment) * monthlyInterestRate;
}
// future value should be at least monthlyInterest * months
assert (futureValue > monthlyInvestment * months) : "FV out of range";

The output that's displayed when an assertion exception is thrown

Exception in thread "main" java.lang.AssertionError: FV out of range
     at FutureValueApp.calculateFutureValue(FutureValueApp.java:152)
     at FutureValueApp.main(FutureValueApp.java:42)

Executing Assertions Example

public class AssertionDemo {
  public static void main(String[] args) {
    int i; int sum = 0;
    for (i = 0; i < 10; i++) {
      sum += i;
    }
    assert i == 10;
    assert sum > 10 && sum < 5 * 10 : "sum is " + sum;
  }
}
Previous | Code assert statements | Enable and disable assertions | Using Exception Handling or Assertions