User defined exceptions are those which are developed by JAVA programmer as a part of application development for dealing with specific problems such as negative salaries, negative ages, etc.
Choose the appropriate package name.
Choose the appropriate user defined class.
Every user defined class which we have choose in step 2 must extends either java.lang.Exception or java.lang.RunTimeException class.
Every user defined sub-class Exception must contain a parameterized Constructor by taking string as a parameter.
Every user defined sub-class exception parameterized Constructor must called parameterized Constructor of either java.lang.Exception or java.lang.RunTimeException class by using super (string parameter always).
For example:
package na; // step1 public class Nage extends Exception // step2 & step3 { public Nage (String s) // step4 { super (s);// step5 } };
Write a JAVA program which illustrates the concept of user defined exceptions?
Answer:
package na; public class Nage extends Exception { public Nage (String s) { super (s); } }; package ap; import na.Nage; public class Age { public void decide (String s) throws NumberFormatException, Nage { int ag= Integer.parseInt (s); if (ag<=0) { Nage na=new Nage ("U HAV ENTERED INVALID AGE..!"); throw (na); } else { System.out.println ("OK, U HAV ENTERED VALID AGE..!"); } } }; import na.Nage; import ap.Age; class CDemo { public static void main(String[] args) { try { String s1=args [0]; ap.Age Ao=new ap.Age (); Ao.decide (s1); } catch (Nage na) { System.out.println (na); } catch (NumberFormatException nfe) { System.out.println ("PASS ONLY INTEGER VALUES..!"); } catch (ArithmeticException ae) { System.out.println ("PASS INTEGER VALUES ONLY..!"); } catch (ArrayIndexOutOfBoundsException aioobe) { System.out.println ("PASS VALUES THROUGH COMMAND PROMPT..!"); } catch (Exception e) { System.out.println (e); } } };
Note:
Main method should not throw any exception since the main method is called by JVM and JVM cannot provide user friendly message.