wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Throwing Exceptions 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 » Programmer Certification (SCJP/OCPJP)
Bookmark "Throwing Exceptions" Watch "Throwing Exceptions" New topic
Author

Throwing Exceptions

Angela lewis
Ranch Hand

Joined: Mar 01, 2004
Posts: 100


This code give a compile time error.
Child.java:8: unreported exception java.sql.SQLException; must be caught or decl
ared to be thrown
doStuff();

But If i do



What i want to know is when i have caught the Exception in doStuff() method which is the method that throws it then why do i have to declare it in someMethod() which calls doStuff() method.

Thanks
Geoffrey Vlassaks
Greenhorn

Joined: May 12, 2004
Posts: 24
When you declare a "throws Exception", you force the caller of your method to: 1) catch your Exception OR 2) throw it furter (like your second code block)..

Greetz
Angela lewis
Ranch Hand

Joined: Mar 01, 2004
Posts: 100
Thanks for replying.
What if the caller does both i.e, catch it as well as throw it further.
Geoffrey Vlassaks
Greenhorn

Joined: May 12, 2004
Posts: 24
Than the same rules apply to the caller of the second method. However, it's possible that the declared exception is never thrown. But you still have to catch it, or throw it further...

Greetz
Angela lewis
Ranch Hand

Joined: Mar 01, 2004
Posts: 100


The method someMethod() needs to either throw the exception or catch it.
But as in this code it does both.
Does this have any implication or is it same as doing one of the two?
Kiran Kumar P
Greenhorn

Joined: Jan 31, 2003
Posts: 18
Doing both doesn't make any sense.You should either catch it or throw it.
Geoffrey Vlassaks
Greenhorn

Joined: May 12, 2004
Posts: 24


In this code, the exceptions are thrown upward. The caller of "anotherMethod()" still has to catch the SQLException, or throw it further. If you don't declare the throws SQLException in "anotherMethod()", you have to catch the exception from "someMethod()"

Hope this helps a bit more..

Greetz
 
Consider Paul's rocket mass heater.
 
subject: Throwing Exceptions
 
Similar Threads
throw exception question
Exception question
Exception handling throw and throws
exam watch question
Exceptions - Handle or Declare requirement