Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

try-catch blocks, exception processing and the HashMap get method

 
Vince Mansel
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was recently experimenting with a try-catch block while dealing with the get method on a HashMap object instance.

The compiler does not require a try-catch (indeed that may be the answer) but in the Java API,
the Map interface (which HashMap implements) says it the get method throws two
different exceptions.

Why doesn't the compiler require a try-catch block around the get method?

When is it "appropriate" to use try catch exception processing other than when it is required by the compiler?
 
paul wheaton
Trailboss
Pie
Posts: 21736
Firefox Browser IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tell us the two exceptions. And then tell us what those exceptions extend.
 
Prateek Parekh
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, you might want to review "Checked" and "Unchecked" exceptions.
 
Vince Mansel
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. I think I got it.

The HashMap extends AbstractMap and implements Map. But according to the API spec,
the HashMap get method does not document that it throws exceptions although the Map interface does and
specifies two: NullPointerException and ClassCastExceptions, both of which extend RuntimeException.

Examining the API for RuntimeException documents:

"A method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught."

Runtime exceptions are unchecked by the compiler.
 
Gary Ba
Ranch Hand
Posts: 161
Firefox Browser Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Runtime exceptions are unchecked by the compiler.

So this means the code needs to fix the runtime exceptions. In this case, check the NULLS.

thanks,
gary
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic