throw – throws
Point of usage
throw keyword is used inside a function. It is used when it is required to throw an Exception logically.
void Demo() throws ArithmeticException, NullPointerException
{
// Statements where exceptions might occur.
throw new ArithmeticException();
}
throws keyword is in the function signature. It is used when the function has some statements that can lead to some exceptions.
void Demo()
{
// Statements where exceptions might occur.
}
Number of exceptions thrown
throw keyword is used to throw an exception explicitly. It can throw only one exception at a time.
// throwing only an IOException
throw new IOException();
throws keyword can be used to declare multiple exceptions, separated by comma. Whichever exception occurs, if matched with the declared ones, is thrown automatically then.
// throwing multiple exceptions
void Demo() throws ArithmeticException, NullPointerException
{
// Statements where exceptions might occur.
}
Syntax
Syntax of throw keyword includes the instance of the Exception to be thrown.
// throwing instance of IOException
throw new IOException();
Syntax of throws keyword includes the class names of the Exceptions to be thrown.
// throwing multiple exceptions by class names
void Demo() throws ArithmeticException, NullPointerException
{
// Statements where exceptions might occur.
}