GNIIT/java

GNIIT/java

what is the different between throw and throws?

View Answers

March 14, 2011 at 11:03 AM

Difference between throw and throws

Whenever we want to force an exception then we use throw keyword. the throw keyword (note the singular form) is used to force an exception. It can also pass a custom message to your exception handling module. Moreover throw keyword can also be used to pass a custom message to the exception handling module i.e. the message which we want to be printed. For instance in the above example we have used -

throw new MyException ("can't be divided by zero");

Whereas when we know that a particular exception may be thrown or to pass a possible exception then we use throws keyword. Point to note here is that the Java compiler very well knows about the exceptions thrown by some methods so it insists us to handle them. We can also use throws clause on the surrounding method instead of try and catch exception handler. For instance in the above given program we have used the following clause which will pass the error up to the next level -

static int divide(int first,int second) throws MyException{









Related Tutorials/Questions & Answers:
GNIIT/java
GNIIT/java  what is the different between throw and throws

Ads