Sep 3, 2011

User defined Exception in java

Steps to create user defined exception in java

step1:       in order to make a class an exception class first of all we need to extend it from any classes of exception
Ex:   class MyExpception extends RunTimeException


step2we than use our class to create and throw the  Exception object

ex: throw new MyException




/*     here the example code i prepare to make u understand..........if the user enter the string above 6 than our exception object rises    ....*/

import java.util.*;
class PragnaniException extends Exception
{
}

class UserDefException
{

 public static void main(String[] args)
 {
  Scanner sc=null;
  try  {
   sc=new Scanner(System.in);
   System.out.println("Enter the string below 6 only");
   String s=sc.next();
   if(s.length()>6)
   {
    throw new PragnaniException();           
  //it is user defined Exception
    //if u enter the string above 6 than our exception object is throw by try block
   }
   System.out.println("\n"+"oops you entered correctly");
  
  }
  catch (Exception e)              
 // here the exception is caught  {
  System.out.println("enter upto 6 chars only");
 }
 }
}