-1

I've been doing some pure Java development recently, and I'm using an external lib that exposes a small number of methods, each of which have the possibility of throwing an Exception.

Eclipse won't let me compile my program unless I wrap each of those calls in a try-catch block. So far, no big deal.

Then I noticed some things, like ArrayList.add(), which throws IndexOutOfBoundsException. How is it that I can call something like this without needing to wrap it in a try..catch? Obv, in this particular case, it would be incredibly irritating if you had to do it each time, but how and why is try-catch enforced in some situations, but not others?

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
divillysausages
  • 7,883
  • 3
  • 25
  • 39
  • 5
    http://docs.oracle.com/javase/tutorial/essential/exceptions/ – JB Nizet May 20 '13 at 14:11
  • Please! Do some research on the net before even posting a question! – Luiggi Mendoza May 20 '13 at 14:12
  • 1
    Specifically, http://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html – Brian Roach May 20 '13 at 14:12
  • 1
    take a look at [java-checked-vs-unchecked-exception-explanation](http://stackoverflow.com/questions/6115896/java-checked-vs-unchecked-exception-explanation) or [why-are-exceptions-named-checked-and-unchecked](http://stackoverflow.com/questions/13104251/why-are-exceptions-named-checked-and-unchecked) – Pshemo May 20 '13 at 14:13
  • thanks for all the links guys - i didn't realise java had 2 types of exceptions. i guess this is a pretty trivial matter when you're familiar with the language – divillysausages May 20 '13 at 14:48

2 Answers2

6

Unchecked exceptions (subclasses of Error or RuntimeException) need no try..catch block, and when there is no try...catch, the method need not to declare itself to be throws (you can, of course, and some consider declaring throws to be a good practice) . On the other hand, checked ones do need the try...catch, or declares throws.

zw324
  • 26,764
  • 16
  • 85
  • 118
3

IndexOutOfBoundsException is an unchecked exception, i.e. it extends RuntimeException or Error, or sub class of either, therefore a try/catch block is unnecessary. From the docs:

Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.

In contrast, checked exceptions require a try/catch block otherwise a compiler error will result.

Community
  • 1
  • 1
Reimeus
  • 158,255
  • 15
  • 216
  • 276