It's not a secret anymore!*
The moose likes Associate Certification (OCAJP 7) and the fly likes try-catch versus throws exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Associate Certification (OCAJP 7)
Bookmark "try-catch versus throws exception" Watch "try-catch versus throws exception" New topic
Author

try-catch versus throws exception

Thomas Hauck
Ranch Hand

Joined: Jun 07, 2011
Posts: 57

If you call a method that throws an exception the programmer must

1) wrap the call to the method in a try statement
and catch the exception OR
2) ensure the calling method throws the same Exception
as the method that is being called.


I have read the following theory with respect to Exceptions.


I need the following statement confirmed.

Proposition:
Whether a call needs to be
1) wrapped in a 'try-catch' block or
2) whether the enclosing method requires a throws clause
depends on the class of reference and not the class of the actual object.

Can someone confirm if the above proposition is true or false?
Roel De Nijs
Bartender

Joined: Jul 19, 2004
Posts: 5126
    
  12

A short code snippet will illustrate your question much better...


SCJA, SCJP (1.4 | 5.0 | 6.0), SCJD
http://www.javaroe.be/
Ted North
Ranch Hand

Joined: Jan 02, 2012
Posts: 192
    
    1

Thomas Hauck wrote:Can someone confirm if the above proposition is true or false?


This seems to be about right. Remember it is only checked-exceptions that need to be caught or declared with a throws clause. Also if the method declares it in a throws clause each calling method all the way back to the main method must also declare it for the code to compile.

I think it is also okay for a super-class to catch the Exception. So, in other words the exact checked-exception thrown does not need to be caught or declared though catching or declaring the exact exception is a better coding practice from what I understand.

Remember checked exceptions are those that extend java.lang.Exception but do not extend java.lang.RuntimeException.

Also, I am fairly certain it is the reference the compiler will watch for and not the actual object type - since the object type is something that will be instantiated at run-time.

I would recommend writing a few small programs at your leisure to test this stuff out and it will make more sense to you.

Regards,

Ted
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: try-catch versus throws exception
 
Similar Threads
Wrapping an Exception
"Handle or Declare" Rule for Checked Exceptions
Catching non-thrown exceptions
Reg. Exception Handling
Exceptions