User-defined exception or Custom exception

There may be situations when we want to create our own Exception that is known as user-defined exception or custom exception. User-defined exceptions are used in Java to customize the exception according to the user need. Using this concept, we can create our own exception with customized message. The following program (Except09.java) demonstrates how to create a user-defined exception in Java using throw and throws keywords:

class LowSalaryException extends Exception { //custom exception which is checked
double salary;

LowSalaryException(double s) { //constructor of custom exception class
salary = s;
}

public String toString() {
return "LowSalaryException: " + salary;
}
}

public class Except09  {

public static void main(String args[]) {
try {
check(25000.75);
check(19375.25);
check(9975.95);
}
catch (LowSalaryException e) {
System.out.println("Exception = " + e);
}
} //end of main() method

static void check(double value) throws LowSalaryException { //declares exception
if (value < 10000) {
throw new LowSalaryException(value); //a custom exception is thrown
}
else {
System.out.println("Salary is OK.");
}
}//end of check() method
}

 

The output of the code is given below:

Salary is OK.
Salary is OK.
Exception = LowSalaryException: 9975.95

 

The preceding program works as follows: LowSalaryException is a custom, checked exception, which extends from Exception class. In main() method , all the calls to static method check() have been placed inside the try block. The check() method includes the  throws clause in its declaration part, can throw a LowSalaryException object using the throw clause in its body under certain conditions. Due to the call check(9975.95), the value of double type variable value will be 9975.95, thereby causing a LowSalaryException object to be thrown, which is to be handled by the catch block corresponding to the try block in main(). Except the call to check(9975.95), all the calls to method check() will print “Salary is OK.”.