Difference between throw and throws in java.

Throws and throw both are keywords in java, used for handling the exception.  When a method is not able to handle the checked exception, it should declared with throws keyword. Throws can be declared with multiple Exceptions separated with comma. Throw is used within the method to throw exception to the caller.

Difference between throw and throws in java.

Throws and throw both are keywords in java, used for handling the exception.  When a method is not able to handle the checked exception, it should declared with throws keyword. Throws can be declared with multiple Exceptions separated with comma. Throw is used within the method to throw exception to the caller.

Difference between throw and throws in java.

Difference between throw and throws in java.

  • Throws and throw both are keywords in java, used for handling the exception.  When a method is not able to handle the checked exception, it should declared with throws keyword. Throws can be declared with multiple Exceptions separated with comma. Throw is used within the method to throw exception to the caller.
  • public void example()throws IOException
     {
     throw new IOException("Hello");
       }
     
  • "Throws" is used to declare an exception but "throw" is used to throw an exception. In simple words, "Throws" is used to handle the exception thrown by "throw".
  • Throw is defined within the method, throws is used in the declaration of method.
  • Using throw, you cannot throw multiple Exceptions. but throws can handle multiple Exceptions.
  • Throws cannot be used anywhere only in  method signature, throw can be used within method as well as in static initialization block too.
   static
     {
     try
       {  throw new Exception("Exception");
         catch(Exception e){}
         }
      }
 

Using throw statement::

  • Throw clause transfer the control to nearest catch block, if the catch block is not there program will terminate.
  • Throw statement can terminate the program.

Using Throws statement:

  • Throws statement is used by method to specify the type of exception it throws. If the method is able to raise an exception but it cannot be handle, It must specify that it will handled by calling method. 

Example: A simple program using throw and throws .

public class Demo 
{

   public void demomethod()throws ClassNotFoundException
   {
	   System.out.println("in method");
	   throw new ClassNotFoundException();
   }


public static void main(String args[]) 
{
	try
	{
	Demo ob=new Demo();
	ob.demomethod();
     }
  catch(ClassNotFoundException e)
  {
	  System.out.println("caught-"+e);
  }

 }

}
Output: After compiling and executing the above program. output will be as follows.

Download  Source Code