I have exception handling being done on every iteration of a while loop. For some reason, when the condition for throwing an exception is true, the exception message is displayed but the program keeps running without interruption. I have never seen this happen before and suspect it is because of the while loop. I MUST check on every iteration for the existence of a null object in my Queue. Another thread suggested using a try clause, so I changed my code to use try clause, but I am still getting the same thing. The exception is thrown but the program does not crash. What is causing this?
Purchase ownedShares;
while (numSharesToSell > 0) {
try {
ownedShares = q.peek();
}
catch(NullPointerException ex) {
throw new IllegalArgumentException("Not enough shares");
}
EDIT 2:
Using isEmpty() does not work either:
Purchase ownedShares;
while (numSharesToSell > 0) {
if (q.isEmpty())
throw new IllegalArgumentException("Not enough shares");
else
ownedShares = q.peek();
// try {
The core error here is not that the exception is not being executed. It IS being executed, and the message "Not enough shares" IS being printed. The problem is that when this occurs the program does not halt. The outer loop continues.
EDIT 3:
The method call I am modifying is wrapped in a try/catch block which prevents any errors I throw from crashing the program. This leaves me to conclude that the person who gave me the skeleton class for this code does not want exceptions to crash the program.