Java user Defined Exception Handling - Hello Exception

/*
Write a java program for exception handling:
To create a user defined exception whenever user input the word "hello".
*/

// java Exception Handling
// user defined exception

import java.util.*;

class userdefinedexception extends Exception
{
     public String toString()
     {
          return ("Hello Exception");
     }
}

class UsrDefException
{
     public static void main(String args[])
     {
          String str;
          Scanner s = new Scanner(System.in);
          try
          {
              System.out.print("Enter name : ");
              str = s.next().trim();
             
              // throw is used to create a new exception and throw it.
              if(str.equalsIgnoreCase("HELLO"))
              {
                   throw new userdefinedexception();
              }
              else
                   System.out.print("Hello "+str);
          }
          catch(userdefinedexception e)
          {
              System.out.println(e) ;
          }
     }
}


/*

Sample output


D:\oopjava>javac UsrDefException.java

D:\oopjava>java UsrDefException
Enter name : asdf
Hello asdf
D:\oopjava>java UsrDefException
Enter name : hello
Hello Exception

D:\oopjava>

*/

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu