javatutelearn.com

Easy Learning


Home

Search Javatutelearn.com :



Java Throw & Throws in Exception Handling

throw keyword

  • It is used to raise exception externally. In other words, the programmer can raise the exception in the program according to a situation.

Example

class A 
{
        void procA() 
		  {
			  try
			  {
			  throw new NullPointerException("Demo "); // This instruction raises an exception.
				}
			  catch(NullPointerException e)
			  {
				  System.out.println(e);
			  }
		  } 
		  public static void main(String Args[])
		  {
				  A a = new A();		
				   a.procA()
		  }
}

Explanation of the program

  • The main function called the method 'procA' which is defined in the class A.
  • Class A generates an external exception called NullPointerException using new operator.
  • The catch block in 'procA' receives NullPointerException and displays the message.

throws keyword

  • It is used to specify exception which a procedure cannot handle.
  • If an exception is listed under throws clause in the method, then it is the responsibility of the caller to handle the exception.

Example

class A 
{
        void procA() throws NullPointerException
		  {
			  throw new NullPointerException("demo"); // This instruction raises an exception.
		  } 
		  public static void main(String Args[])
		  {
			 try
			  {
				  A a = new A();		
				   a.procA();
			  }
			  catch(NullPointerException e)
			  {
				  System.out.println(e);
			  }
		  }
}

Explanation of the program

  • Class A throws an exception, but it is not handling the exception.
  • Therefore, class A has to inform to calling function that it should safe guard itself by exceptions.
  • Keyword throws is used to inform to calling function about name of the exception.
  • In this program, exception NullPointerException is raised by class A, but class A is not handling this exception.
  • It is the responsibility of calling function (in this example 'main()') to put procedure named 'procA()' in the try..catch block to handle the exception NullPointerException.


© Copyright 2016-2024 by javatutelearn.com. All Rights Reserved.