Java- User Defined Exceptions

User Defined Exceptions

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.

3 Steps to developing user defined exceptions

  • Choose the appropriate user defined class must extends either java.lang.Exception or java.lang.RunTimeException class.

  • That class must contain a parameterized Constructor by taking string as a parameter.

  • Above constructor must call super constructor with string Ex : super(s)

Example

For implementing example, we must create 3 classes

  1. User defined Exception class

  2. A class with a method which throws User defined Exception

  3. Main class which calls above method


1.User Defined Exception class

public class NegativeNumberException extends Exception {

  public NegativeNumberException(String s) {
    super(s);
  }
  
}

2.A class with a method which throws User defined Exception throws & throw

public class Salary {
  public void show(int sal) throws NegativeNumberException {
    if (sal < 0) {
      throw new NegativeNumberException("Salary Should be >1");
    } else {
      System.out.println("Your Sal is :" + sal);
    }
  }
}

3.Main class which calls above method

public class UserMain {
  public static void main(String[] args) {
    Salary salary = new Salary();
    try {
      salary.show( - 100);
    } catch(NegativeNumberException e) {
      e.printStackTrace();
    }
  }
}
excep.NegativeNumberException: Salary Should be > 1
at excep.Salary.show(Salary.java: 8)
at excep.Salary.main(Salary.java: 18)

In Real time CSW Id Start with A1 & Contains 8 digit number, so if given ID not met the requirement Throws CSWException