what is difference between throw and throws in exception?
Answer Posted / rhine
One declares it, and the other one does it.
Throw is used to actually throw the exception, whereas throws is declarative for the method. They are not interchangeable.
public void myMethod(int param) throws MyException
{
if (param < 10)
{
throw new MyException("Too low!);
}
//Blah, Blah, Blah...
}
The Throw clause can be used in any part of code where you feel a specific exception needs to be thrown to the calling method.
If a method is throwing an exception, it should either be surrounded by a try catch block to catch it or that method should have the throws clause in its signature. Without the throws clause in the signature the Java compiler does not know what to do with the exception. The throws clause tells the compiler that this particular exception would be handled by the calling method.
| Is This Answer Correct ? | 0 Yes | 0 No |
Post New Answer View All Answers
What does those terms actually mean included in the j.d.k i.6?
What is difference between final and finally in java?
What is java used for?
What are the three types of design patterns?
Can a serialized object be transferred via network?
What is the use of http-tunneling in rmi?
How many types of the indexof method are there for strings?
What does substring mean?
What is meant by data hiding in java?
Difference between string, stringbuffer and stringbuilder?
What is a parameter example?
What are the differences between checked exception and unchecked exception?
What is the difference between processes and threads?
What is the use of static methods?
Java is pass by value or pass by reference? Explain