Java throws Keyword
throws statement
Throws keyword allows us to execute multiple exceptions from a method.
If a method is generating an exception bu cannot handle it, then it is the job of method to specify the task to protect them from an Exception.
The exception that can be generated by method must be thrown by using throws clause otherwise the compile time error will be generated.
Syntax
type methodName() throws ExceptionType1,ExceptionType2...ExceptionTypeN
{
// body of the method
...
...
throw new ExceptionType ("String"); // required for executing catch block.
//or
throw ThrowableInstance
}
Above method can be written inside the other try block or any other method. Compiler calls to particular catch block from the throw statement.
Example
class ThrowsTest
{
static void throwsMethod() throws ArithmeticException
{
int a = 10, b = 0 , c;
c = a/b;
throw new ArithmeticException ("Error");
}
public static void main(String args[])
{
try
{
throwsMethod();
}
catch(ArithmeticException e)
{
System.out.println("Divided by zero error");
}
}
}