THROW & THROWS

Difference Between Throws & Throw
1. Throws clause used to declare an exception while Throw keyword used to throw an exception explicitly.
2. Throws is followed by exception class names while Throw is followed by an instance variable.
3.Throws clause is used with method name while Throw used inside method body to invoke an exception.
4. Example of Throw
try
           {
throw new Exception("Something went wrong!!");
   }
 catch(Exception exp)
 {
 System.out.println("Error: "+exp.getMessage());
}

Example of Throws:
public void sample() throws ArithmeticException{
 //Statements
}

5. By using Throw keyword in java you cannot throw more than one exception but using throws you can declare multiple exceptions.
   For Example:
Throw:
throw new ArithmeticException("An integer should not be divided by             zero!!")
throw new IOException("Connection failed!!")
Throws:
throws IOException, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException

No comments:

Post a Comment

JAC Board Computer || IIT 2025 || Introductory Information Technology || Class 10 || Practical Examination 2025

Marks Division HOE 30 Marks IT Application Report File 20 Marks Viva - Voce 10 Marks 1) Write an HTML code to generate a web p...