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 is the difference between array list and vector in java?
What is the difference between sop and work instruction?
What does the “static” keyword mean?
What is java in layman terms?
4.1 Supply contracts (in the form of comments specifying pre- and post conditions) for the enqueue() method of the LinkedQueue class given in the Appendix. (2) 4.2 Let Thing be a class which is capable of cloning objects, and consider the code fragment: Thing thing1 = new Thing(); //(1) Thing thing2 = thing1; //(2) Thing thing3 = (Thing) thing1.clone(); //(3) Explain how the objects thing2 and thing3 differ from each other after execution of the statements. (
What is a values collection view ?
What is a lambda expression ? What's its use ?
What is parameters example?
What are aggregate functions explain with examples?
What isan abstract class and when do you use it?
What does business logic mean?
What is an example of a keyword?
How do you override a private method in java?
What are the basic control structures?
What do you mean by local class?