• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

throw and throws!!

 
Ranch Hand
Posts: 232
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi folks,
could you please explain me what's the difference between throw and throws? what is a particular situation that each one these is used?
thanks.
 
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi
throw is a "verb" meaning it will throw the specified exception when the code is executed.
throws is just a declaration that says "the code might throw the specified exception at runtime".
now, usage of throw would be,
if you have a class that does division of two integer numbers then in your code you can write like,
public double divide(int i,int j) throws DivideByZeroException {
if ( j == 0 )
throw DivideByZeroException("You should better practice math");
return i/j;
}
here, throw will actually throw the exception when j==0 as we should not try to divide by zero.
BUT the throws will declare the method as "it can throw the exception" so the using class knows what can go wrong while using the divide() method.
regards
maulin
reply
    Bookmark Topic Watch Topic
  • New Topic