File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Cattle Drive and the fly likes try-catch blocks, exception processing and the HashMap get method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » This Site » Cattle Drive
Bookmark "try-catch blocks, exception processing and the HashMap get method" Watch "try-catch blocks, exception processing and the HashMap get method" New topic
Author

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

Vince Mansel
Greenhorn

Joined: Feb 14, 2010
Posts: 18
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

Joined: Dec 14, 1998
Posts: 20635
    ∞

Tell us the two exceptions. And then tell us what those exceptions extend.


permaculture Wood Burning Stoves 2.0 - 4-DVD set
Prateek Parekh
Ranch Hand

Joined: Apr 17, 2010
Posts: 34
Also, you might want to review "Checked" and "Unchecked" exceptions.
Vince Mansel
Greenhorn

Joined: Feb 14, 2010
Posts: 18
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

Joined: Oct 23, 2009
Posts: 161

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

star chaser..
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: try-catch blocks, exception processing and the HashMap get method