• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Difference between throw and throws

 
Vasiq Molvizadah
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys....i'm new to Java and i've been reading Head First Java book, there is one part which i didn't get it is...
What's the difference between "throw" and "throws" clause ...and why do we use these two ???
Thanks for reading it....
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One defines what a method throws. One actually throws something. Did you search for Java documentation covering those keywords?
 
Campbell Ritchie
Sheriff
Posts: 48374
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The "throw" keyword causes an Exception object to be created. The throws keyword allows one to warn the compiler that a certain method might throw an Exception.
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure I'd say that "throw" *causes* an exception object to be created; you still need to create the exception, no?
 
Rob Spoor
Sheriff
Pie
Posts: 20493
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Correct. That's what the "new" after the "throw" does. You can also throw existing exceptions, like "throw e;".
 
Campbell Ritchie
Sheriff
Posts: 48374
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're right; that is more precise than what I wrote.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic