Java Exception throws keyword

Introduction

If a method can throw exception, it must include a throws clause in the method's declaration.

A throws clause lists the types of exceptions that a method might throw.

This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses.

This is the general form of a method declaration that includes a throws clause:

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

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

public class Main {  
  static void throwOne() throws IllegalAccessException {  
    System.out.println("Inside throwOne.");  
    throw new IllegalAccessException("demo");  
  }  /*  w  w  w  . j  a  va  2  s  . com*/
  public static void main(String args[]) {  
    try {  
      throwOne();  
    } catch (IllegalAccessException e) {  
      System.out.println("Caught " + e);  
    }  
  }  
} 



PreviousNext

Related