Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

throw throws

 
feroz muhamed
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the difference btwn throw and throws?
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
throw is used normally like this
throw new Exception(). This throws a new Exception wich must be catched or passed further to the calling class or method.
throws is used in the method signature. This tells the compiler that this method doesn't take care of the given exception but simply passes it to the caller. So every class/method which calls that method must either catch this exception or itself throws it.
 
Ravi Kotaru
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Throw:
Before you can catch an exception, some Java code somewhere must throw one. Any Java code can throw an exception: your code, code from a package written by someone else (such as the packages that come with the Java development environment), or the Java runtime system. Regardless of who (or what) throws the exception, it's always thrown with the Java throw statement.
Throws:
this can be used to inform JRE that this method may throw some type of exception.
Example:
public Object pop() throws EmptyStackException {
Object obj;
if (size == 0)
throw new EmptyStackException();
obj = objectAt(size - 1);
setObjectAt(size - 1, null);
size--;
return obj;
}
Ravi
 
Marilyn de Queiroz
Sheriff
Posts: 9059
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
throw - a command to "throw an exception"
throws - a declarative statement stating that "this method throws an exception"
 
Leslie Chaim
Ranch Hand
Posts: 336
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
throw - is a verb
throws - is an action verb
 
Nathaniel Stoddard
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I may throw in my 2 cents here ...
You may only "throw" objects, whereas "throws" is a declaration, and thus can only be defined by a class.
That is, you declare a function to throw a type (class) of object with the "throws" keyword, but when the time comes to actually throw an object of that class, you do so with the "throw" keyword.
public void throwMe() throws Exception /* <-- that's a class */ {
throw new Exception(); // <--- that's an object
}
Wow, I think that will even compile.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic