Activity 4.4 - A program which throws an exception
Topic
In this activity, we witness a Java exception being thrown in a
fairly spectacular manner.
Materials
In addition to the Solution document, the project for this
activity contains two classes:
- GreedyClass,
containing a method grabSomeMemory(int
n) that tries to allocate enough memory for an array
of int
variables with n
elements (i.e. 4*n
bytes);
- Main,
which creates an instance of the GreedyClass
class and invokes a method, requesting an amount of memory that is
likely to be absurd, at least at the time of writing!
Instructions
- Run the project. You will find the
program halts and reports an exception. Normally, exceptions result
in messages that are quite informative, but this case is possibly a
bit extreme, so we don't get told too much!
- Confirm that this exception does not occur for
more modest memory allocation requests. In the main
method of Main,
decrease the amount of memory requested by a factor of 1000, like
this:
final int AMOUNT = 1000*1000;
Run the project again - you should find that it completes
successfully.
- Just for interest, in the main
method of Main,
try the effect of attempting to increase the amount of memory
requested by a factor of 1000 compared to the original program, like
this:
final int AMOUNT = 1000*1000*1000*1000;
What happens this time?