top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the difference between throw and throws in Java?

+1 vote
648 views
What is the difference between throw and throws in Java?
posted Oct 24, 2016 by Pooja

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote
 
Best answer

Throw vs Throws in java

  1. Throws clause in used to declare an exception and thow keyword is used to throw an exception explicitly.

  2. If we see syntax wise than throw is followed by an instance variable and throws is followed by exception class names.

  3. The keyword throw is used inside method body to invoke an exception and throws clause is used in method declaration (signature).

for e.g.

Throw:

....
static{
try {
throw new Exception("Something went wrong!!");
} catch (Exception exp) {
System.out.println("Error: "+exp.getMessage());
}
}

....

Throws:

public void sample() throws ArithmeticException{
 //Statements

.....

 //if (Condition : There is an error)
ArithmeticException exp = new ArithmeticException();
 throw exp;
...
}
  1. By using Throw keyword in java you cannot throw more than one exception but using throws you can declare multiple exceptions. PFB the examples.

for e.g.

Throw:

throw new ArithmeticException("An integer should not be divided by zero!!")
throw new IOException("Connection failed!!")

Throws:

throws IOException, ArithmeticException, NullPointerException, 
ArrayIndexOutOfBoundsException
answer Oct 24, 2016 by Karthick.c
Thanks for the help
welcome!
+1 vote

Java throw example

void m(){  
throw new ArithmeticException("sorry");  
} 

Java throws example

void m()throws ArithmeticException{  
//method code  
} 

Java throw and throws example

void m()throws ArithmeticException{  
throw new ArithmeticException("sorry");  
}
answer Jan 6, 2017 by Ajay Kumar
...