2

I have a String array tmp got by String[] tmp = line.split(",");

Then,

I got java.lang.ArrayIndexOutOfBoundsException: 3 on code

assert tmp.length == 4;
int r = Integer.parseInt(tmp[3]);   ----error line

and java.lang.ArrayIndexOutOfBoundsException: 2 on code

assert tmp.length == 3;
String name = tmp[2];    -----error line

I do not think this error is reasonable. The assert statement passes correctly and how can a array with .length=4 having no element indexed 3? Could anyone tell me why...

Litchy
  • 355
  • 1
  • 4
  • 18

2 Answers2

3

As stated in the comments, the problem here is that you did not activate the assertions in the JVM options

In command line java MyProgram -ea

For Eclipse, see this answer.

For IntelliJ, see this answer.

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
2

By default, assertions are disabled and you should enable them using either of below command-line switches:

  • -ea
  • -enableassertions

You can check the documentation for more package and sub-package finer grained activation.

For arguments or variables validation, you should use a dedicated Assertion library or simply craft yours.

A lightweight and fluent one should be the valid4j:

//...
Assertive.ensure(tmp.length == 4, "The split result array must have 4 elements: (%d)", tmp.length);
tmarwen
  • 15,750
  • 5
  • 43
  • 62