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
Is a char always 1 byte?
Will the jvm load the package twice at runtime?
How many bits is size_t?
What is function and its uses?
What does method mean?
Explain java code for recursive solution's base case?
What is prefix of a string?
What is an object in java and how is it created?
Which sorting is best in java?
What is mean by encoding?
What is the difference between access specifiers and access modifiers in java? 16
What is hasnext in java?
What does a void function return?
What are the disadvantages of using inner classes?
What is a void method java?