• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Throwing Exceptions

 
Angela lewis
Ranch Hand
Posts: 100
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 24
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 100
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for replying.
What if the caller does both i.e, catch it as well as throw it further.
 
Geoffrey Vlassaks
Greenhorn
Posts: 24
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 100
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 18
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Doing both doesn't make any sense.You should either catch it or throw it.
 
Geoffrey Vlassaks
Greenhorn
Posts: 24
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic