Saturday 30 December 2017

java - Why is try/catch needed in some cases but not others?





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?


itemprop="text">
class="normal">Answer



href="http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html"
rel="noreferrer">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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...