1.

Differentiate Between Throw And Throws In Exception Handling.

Answer»

Throw clause is used when a user wants to throw a customized explicit exception. Throw clause is used if there is a need for a specific exception to be thrown to the CALLING method.

try {

if (age>=100) {throw new AgeBarException (); //This is a customized exception

} else {

....}

}

} catch (AgeBarException ex) {

...code to handle Exception.....

}

Throws Clause lists all the EXCEPTIONS that piece of code MIGHT throw. Throws clause provides a warning to the invoking method that these are the list of exceptions it might throw and all these need to be handled.

  • Throws is used to declare an exception whereas throw clause is used to explicitly throw an exception.
  • throws clause is SPECIFIED in the method signature whereas throw clause is used WITHIN a method.
  • Throws clause is often followed by a class whilst throw clause is often followed by an instance.

Throw clause is used when a user wants to throw a customized explicit exception. Throw clause is used if there is a need for a specific exception to be thrown to the calling method.

try {

if (age>=100) {throw new AgeBarException (); //This is a customized exception

} else {

....}

}

} catch (AgeBarException ex) {

...code to handle Exception.....

}

Throws Clause lists all the exceptions that piece of code might throw. Throws clause provides a warning to the invoking method that these are the list of exceptions it might throw and all these need to be handled.



Discussion

No Comment Found