• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

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

 
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?
 
Trailboss
Posts: 23216
IntelliJ IDE Firefox Browser 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.
 
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.
 
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
 
I'm sure glad that he's gone. Now I can read this tiny ad in peace!
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic