You are here:   HomeJava ProgrammingException HandlingThrows Clause in Java Example
by Dinesh Thakur Category: Exception Handling

The basic principle of Java error handling mechanism is that an exception must either be handled by the method in which it is raised or passed along the call chain for another method to handle it. Suppose a method throws an exception, that is neither a subclass of RuntimeException nor of Error i.e. if it throws a checked exception, then Java requires that the method either handles it or declares it. If the method does not handle the checked exception then the method must declare it using the throws keyword.

The following example demonstrates the use of throws clause

import java.io.IOException;

public class ThrowsClause
{
     static boolean guess() throws IOException
     {
         char ch='r';
         System.out.print("Guess any Character(a-z) : ");
         char n=(char)System.in.read();
         return(ch==n);
      }
     public static void main(String[] args)
     {
          boolean result;
          try
         {
              result=guess();
              if(result==true)
                 System.out.println("Your Guess is Perfect");
              else
                 System.out.println("Your Guess is Incorrect");
          }
              catch(IOException e)
          {
                 System.out.println("Error May be Occured in Input");
           }
      }
}

Throws Clause in Java Example



What's New and Popular