156
bjorngi
8y

Did this on my first programming exam.

int index = 0
int value = 0
try {
while true {
value += array[index]
index++
}
} catch NullPointerException {
System.out.print("Sum: " + value)
}

The task was to add together all numbers in an array.

I somehow aced the exam, but got called in to teachers office this is not the way to use exceptions.

Comments
  • 41
    Surely ArrayIndexOutOfBoundsException instead of NullPointerException, no?
  • 8
    @linux-colonel you are probly right. Just did it from memory. It's been a while since school, and java ☺️
  • 3
    I guess it would be a good solution for a stream where you don't know the actual size so you could argue the implementation of the array has count :)
  • 6
    Surprisingly this is exactly how for works in Python. I wish Guido meet your teacher.
  • 1
    I just realized how brilliant it can be! ~Random Microsoft Windows programmer :)
  • 3
    LOL..... Seems you just gave away the answer to the first contest problem sort of.... Would be a very bad solution though...

    https://hackerrank.com/challenges/...
  • 2
    In Erlang they recommend you use exception handling when doing things like traversing a tree

    That way you don't have to go back through the recursive call stack once you find the value you're looking for, you instead just jump right back up to the handler, saving a lot of potential time
Add Comment