Discussion of Activity 4.4 - A program which throws an exception
Here are the expected results at each stage of this activity:
- You should find that
the program halts and reports an OutOfMemoryError
exception. This type of exception is not at all common and has only
come about because we have provoked it deliberately.
- The exception should not occur this time, as most
systems should be able to allocate one million ints.
If it does still occur, reduce the amount of memory requested again
to 1000
ints. This should work on any reasonable system. The
program should complete normally and print the message:
Successfully allocated
- You might think that this would have the same
effect as the first experiment, after an attempt to allocate a
million million ints
(1000*1000*1000*1000).
However, an int
variable in Java cannot store a number as big as this, so the
calculation "wraps around" to a negative value, and you
should get messages like this:
Try to allocate memory for -727379968 ints
java.lang.NegativeArraySizeException
So the program does fail to complete, but with an exception
indicating an attempt to construct an array whose size is a negative
number - tricky!