User-defined exceptions

  1. All these times we have been using predefined exception classes whose objects were created by JVM, because of predefined logical errors.
  2. In a similar manner, we can define our own exceptions classes whose objects will be created when user defined logical errors occur
  3. Strictly speaking, the user defined logical error is not a logic error from the JVM’s point of view.
  4. Whenever an erroneous situation is expected to occur in a function, then we can terminate the function in the middle by using user-defined exceptions.
  5. In this middle by using user-defined exceptions.

 

The following program illustrates the use of user defined Exceptions:

Class Invalid Age Exception extends exception

{

Public string to string ()

{

String s1 = “Invalid Age Exception: Invalid age value passed”;

Return (s1);

}

}

Class Emp

{

Public float genpension (int age, float sal) throws Exception

{

Float pen =0;

If (age> 45 && age<100)

{

Pen = (age*sal)/100;

}

Else

{

Throw new Invalid Age Exception ();

}

Return (pen);

}

Class Test

{

Public static void main (string args [ ])

{

Int age = Integer .parseInt (args [0]);

Float sal = float. parsefloat (args [1]);

Emp e = new Emp ();

Try

{

Float p = e. getpension( age,sal);

System. Out. Prinln(p);

}

Catch (Exception e1)

{

System. Out. Prinln(e1);

}

System. Out. Prinln(age);(

System. Out. Prinln(sal);

}

}

 

Explanation:

  • First define a user defined exceptions class: Invalid Age Exception.
  • Since Invalid Age Exception class object is generated because of simple logical error, it should be a sub – class of Exceptions class. Thus, we have to extend Exception class to our class.
  • Class Emp has one function get a pension () which takes two arguments and calculates the pension and then returns the pension value.
  • In a class test, we call the get pension () method to calculate the pension of an employee.

 

User Defined Exceptions Homework Help