GeekInterview.com
   Home |  Tech FAQ  |   Interview Questions |  Placement Papers |  Tech Articles |  Learn |  Freelance Projects |  Online Testing |  Geeks Talk |  Job Postings |  Knowledge Base | Site Search |  Add/Ask Question

  GeekInterview.com  >  Interview Questions  >  J2EE  >  Core Java

 Print  |  
Question:  Please Give me an example for User defined Exception



November 11, 2005 08:52:39 #6
 nagaraju J2EE Expert  Member Since: November 2005    Total Comments: 4 

RE: Please Give me an example for User defined Excepti...
 

in case of system defined exceptions,if any violation occured while executing the code,it will create a exception object and throw that object.

in catch block u catch it and give appropriate message.

userdefined exception:in case of user defined exceptions,create a class as a subclass of java.lang.Throwable and implement   toString() method in your class.

Example:

public class UserException extends java.lang.Throwable{

private String ex;

public UserException()

{

}

public UserException(String s)

{
    ex=s;

}

public String toString()

{

return ex;

}

}

public class App{

public static void main(String args[])

{

//take the value from key board   if it is equal to exception generate user defined exception

InputStreamReader isr=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(isr);

try{

if(br.readLine()=="exception"){


    UserExceptin ue=new User Exception("this is the user defined exception");

throw ue;

}

}

catch(Exception e)

{
System.out.println(e);

}

}

     

 

Back To Question