I thought that array bounds checking needed two comparisons; however, ...

  • Thread starter Casey Hawthorne
  • Start date
C

Chris Smith

Pedro said:
The following code snippet fails with an ArrayIndexOutOfBoundsException

char[] msg = {'m', 'o', 'o', 'b'};
for(int i = msg.length - 1; i < msg.length; i--)
{
System.out.print(msg);
}


The code is obviously broken. I don't understand why you'd ever expect
it *not* to fail with an exception. It's pointless to try and
anticipate all possible bugs in code and write code to detect them and
prevent exceptions. It's better for the code above to fail with the
IndexOutOfBoundsException and thus let the programmer know that
something is seriously wrong during testing.

After all, if you detected that something is wrong in your own code,
what would you do? The best choice is probably to throw an exception,
but that raises the question of why you write the test code in the first
place.

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
R

Roedy Green

The following code snippet fails with an ArrayIndexOutOfBoundsException

char[] msg = {'m', 'o', 'o', 'b'};
for(int i = msg.length - 1; i < msg.length; i--)
{
System.out.print(msg);
}

You do three types of sanity checking your computer programs:

1. to check for expected error conditions.

2. to verify your code does not contain bugs.

3. to make sure when your program goes insane, you find out about it
as soon as possible before it destroys all traces of what went wrong.

For (1) you typically code explicit checks.

For (2) you use asserts which can be turned off once you are sure the
code is solid.

For (3) you trust the run time array subscript out of bounds and null
pointer checking.A long time ago, someone pointed out an efficiency
that the Java run time could use to avoid doing two compares for a
subscript bounds check by using a unsigned compare to implement (3).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,681
Members
48,796
Latest member
Greg L.

Latest Threads

Top