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


Please Help Members By Posting Answers For Below Questions

What is the difference between array list and vector in java?

509


What is the difference between sop and work instruction?

487


What does the “static” keyword mean?

584


What is java in layman terms?

531


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. (

1418






What is a values collection view ?

685


What is a lambda expression ? What's its use ?

565


What is parameters example?

558


What are aggregate functions explain with examples?

528


What isan abstract class and when do you use it?

847


What does business logic mean?

508


What is an example of a keyword?

549


How do you override a private method in java?

509


What are the basic control structures?

501


What do you mean by local class?

519