Friday, October 16, 2015

Difference between throw and throws

1. A throw statement can be used to throw an Exception explicitly from the code where as a throws statement just declares that an Exception can be thrown. It doesn't actually throw and Exception

2.
--A throw statement is followed by an object of type Throwable e.g.

Exception e1=new Exception(); 
throw e1;

-- A throws statement is written in the definition of a constructor or a method e.g.

void m1() throws Exception{
    // any code here
}

3. A throw statement is an executable statement where as a throws statement is just a declarative statement

4. A throw statement is actually used at run time.. where as a throws statement is referred by the compiler at compile time. After compilation, throws has no effect at run time

5. A throw statement is used to throw both Checked and Unchecked Exceptions, while a throws statement should be used if an un-handled Checked exception is throws from a method or constructor.

No comments:

Post a Comment