Exception throws


If a method is capable of causing an exception that it does not manage, it must specify this behavior so that the callers to the method can protect themselves against this exception. You do this by including a throws clause in the declaration of the procedure. A throws clause displays a list of exceptions that a method can throw. This is necessary for all exceptions, except for errors or runtime exception types or any of their subclasses. All exceptions that any method may throw must be declared in the throws clause. If they are not, a compilation-time error will result.

type method-name(parameter-list) throws exception-list
{
 //body of the method
}

Here, the exception list is a comma-separated list of exceptions that any method can throw.

The following is an example of an incorrect program that attempts to throw an exception that it did not catch. The program will not compile because it does not specify a throws clause to express this fact.

Program
// This program contains an error and will not compile.
class ThrowsExample{
 static void Demo(){
  System.out.println("Inside Demo.");
  throw new IllegalAccessException("demo"); 
 }
 public static void main(String args[]){
  Demo();
 }
}

To make this example compile, you need to make two changes. First, you need to declare that Demo() throws IllegalAccessException. Second, main() must define a try/catch statement that catches this exception.

Program
// This is now correct.
public class Main {
  static void Demo() throws IllegalAccessException{
  System.out.println("Inside Demo.");
  throw new IllegalAccessException("demo"); 
 }
  public static void main(String[] args) {
    try{
     Demo();
    }
    catch(IllegalAccessException e){
     System.out.println("Caught : " + e);
    }
  }
}