Thursday, 23 January 2014

throws JAVA KEYWORD

Java:Using throws in Exception Handling

How to throws exceptions in java with example

The throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing check up before the code being used.


The general form is as shown below:

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

Example:

import java.io.IOException;  
class Simple{  
  void m()throws IOException
{  
    throw new IOException("device error");//checked exception  
  }  
  void n()throws IOException
{  
    m();  
  }  
  void p()
{  
   try{  
    n();  
   }catch(Exception e){System.out.println("exception handled");
}  
  }  
  public static void main(String args[])
{  
   Simple obj=new Simple();  
   obj.p();  
   System.out.println("normal flow...");  
  }  
}  


Output:
exception handled
normal flow...


No comments:

Post a Comment