Exceptions (Cont.)


The throw Keyword
The throw statement allows you to create a custom error. The throw statement is used together with an exception type. There are many exception types available in Java, for example, The exception type is often used together with a custom method. The following program throws an exception if age is below 18 (print “Access denied!”). If age is 18 or older, print “Access granted!”:

ThrowDemo.java (with a throw keyword)
public class ThrowDemo {
  public static void main( String[ ] args ) {
    checkAge( Integer.parseInt( args[0] ) );
  }
  static void checkAge( int age ) {
    if ( age < 18 )
      throw new ArithmeticException( "Access denied - You must be at least 18 years old." );
    else
      System.out.println( "Access granted!" );
  }
}
shell> java ThrowDemo            




      I was banging my head against the wall (feeling angry or annoyed)    
      trying to lose weight without exercising.