Throws
In some situations methods can cause exceptions which can be handle by throws clause by including it in the method declaration as follows
type method-name(parameter-list) throws exception-list
{
// body of method
}
exception-list---these are the list of exceptions that method can throw, except Error, Run-time Exceptions and its sub classes all the exceptions that method can throw should be declared in this list which are separated by comma.
// example for throws clause.
public class ThrowsDemo
{
static void throwOne() throws IllegalAccessException //should throws the exception throw in method.
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo"); //to catch this exception try catch should be used in main() method
}
public static void main(String args[])
{
try
{
throwOne();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}
}
}
Output:
Inside throwOne.
Caught java.lang.IllegalAccessException: demo