File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes throw and throws!! Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "throw and throws!!" Watch "throw and throws!!" New topic
Author

throw and throws!!

Brian Smith
Ranch Hand

Joined: Oct 26, 2002
Posts: 232
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.
Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1865
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


1. Have fun @ http://faq.javaranch.com/java/JavaRaq
2. Looking for simple infix2postfix conversion and postfix evaluation package? Click here
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: throw and throws!!
 
Similar Threads
Throws and throw
diff b/w Throw and Throws
throw throws
Difference
throws and throw