User Defined exception in Java | Java custom exception examples

In Java programming, it is possible to create our own exceptions and such exception are called user-defined exceptions in Java.

The exception class is a predefined class. Any user-defined exception created by us must be a subclass of the predefined Exception class and created by extending the Exception class.

Read More

  1. Exception Handling in Java: Hierarchy Example and Types
  2. Exception Handling in Java with Examples
  3. Exception Handling try catch finally blocks in Java
  4. Throw and Throws Keywords in Java

What is user defined (custom) exception in java

An Exception that is defined by the user/ programmer is known as a user-defined or custom exception.

example

  1. Checking user age if not valid age throw an exception
  2. If not in a specified time period then throw an exception
  3. If the user name and password are incorrect then throw an exception

All above exceptions are created by the user and throw when required.

How to throw user defined exception in java

 The throw and throws keywords are used for implementing user-defined exceptions. 

throw: throw keyword is used to throw an exception explicitly from a method or form a block.   

for instance

 throw new NumberIsGreaterException();

 Here new NumberIsGreaterException();

is creating a new exception and throwing it.

throws: throws keyword is used with a method signature that informs that the method can throw a mentioned exception.   

public Scanner​(File source)
        throws FileNotFoundException

Here Scanner is class and the above-mentioned Scanner represents the constructor call, On the constructor call of above, we have to handle File not found Exception.

how to create user defined exception in java

  1. Create a class
  2. Extend the Exception class
  3. Create a String argument constructor to pass the custom messages.
public class Exception1 extends exception{
      Exception1(String msg){
         super(msg);
         //or print message   
} 

Examples of User Defined Exception in Java

Example1:   write a program to take a number from a user by using the command line argument during run time. if the user will enter more than 100 then generate the user-defined exception MyException.

class NumberIsGreaterException extends Exception {
    NumberIsGreaterException() {
        System.out.println("User Exception ");
    }
}
public class TestMain {
    public static void main(String args[]) {
        try {
            int m = Integer.parseInt(args[0]);
            if (m > 100) {
                throw new NumberIsGreaterException();
            }
        } catch (NumberIsGreaterException e) {
            System.out.println(e);
        }
        System.out.println("After try, and catch ");
    }
}
java TestMain 111
User Exception 
NumberIsGreaterException
After try, and catch  

Explanation: In the above program, the name of the user define exception is NumberIsGreaterException. 

In the above program, the user enters the number 111 during run time using a command-line argument.

Here the value of “m” is greater than 100 therefore  “throw newNumberIsGreaterException ();” this throw statement throws the exception and catches by the catch block but before throw “NumberIsGreaterException ()” constructer will call.

User defined exception in java program to check age is valid or not

invalid age exception in java : invalidageexception

InvalidAgeException.java

class InvalidAgeException extends Exception {
    InvalidAgeException(String s) {
        super(s);
    }
}

CheckAge.java

import java.util.Scanner;
public class CheckAge {
    void validateAge(int age) throws InvalidAgeException {
        if (age <= 100 && age > 0) {
            System.out.println("Valid age");
        } else {
            throw new InvalidAgeException("Age is not valid");
        }
    }
    public static void main(String[] s) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your age");
        int age = sc.nextInt();
        CheckAge ck = new CheckAge();
        try {
            ck.validateAge(age);
        } catch (InvalidAgeException e) {
            System.out.println("Invalid Age " + e.getMessage());
        }
    }
}

Output

D:\Test Java>javac CheckAge.java 
D:\Test Java>java CheckAge
Enter your age
23
Valid age
D:\Test Java>java CheckAge
Enter your age
112
InvalidAgeException: Age is not valid
        at CheckAge.validateAge(CheckAge.java:9)
        at CheckAge.main(CheckAge.java:19)

user defined exception in java example to check a time is in range or not, if time is not in range then throw custom exception

InvalidTimeException.java

class InvalidTimeException extends Exception {
    InvalidTimeException(String s) {
        super(s);
    }
}

CheckTime.java

import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;
public class CheckTime {

    void validateTime(String time) throws InvalidTimeException, ParseException {
        String from = "08:12:00";
        String to = "11:12:00";

        Date date_from = null;
        Date date_to = null;
        Date dateNow = null;
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        date_from = formatter.parse(from);
        date_to = formatter.parse(to);
        dateNow = formatter.parse(time);


        if (date_from.before(dateNow) && date_to.after(dateNow)) {
            System.out.println("Valid Time");
        } else {
            throw new InvalidTimeException("Time is not in range");
        }
    }

    public static void main(String[] s) {
        String n = "09:10:00";
        CheckTime ck = new CheckTime();
        try {
            ck.validateTime(n);
        } catch (InvalidTimeException e) {
            System.out.println("Invalid Time " + e);
        } catch (ParseException e) {
            System.out.println("ParseException " + e);
        }

    }
}

Output

 
D:\Test Java>java CheckTime
Valid Time

Example: Write a program to create a user-defined exception in Java to check whether a given name exists or not. If the name doesn’t exist then throw a custom exception.

InvalidNameException.java

class InvalidNameException extends Exception {
    InvalidNameException(String s) {
        super(s);
    }
}

CheckName.java

import java.util.Scanner;
public class CheckName {

    void validateName(String name) throws InvalidNameException {

        String[] names = {
            "Ram",
            "Mohan",
            "Sohan",
            "Mita",
            "Neeta",
            "Anita"
        };
        boolean found = false;
        for (String n: names) {
            if (n.equalsIgnoreCase(name)) {
                found = true;
                break;
            }
        }
        if (found) {
            System.out.println("Valid Name");
        } else {
            throw new InvalidNameException("Not a valid name");
        }

    }


    public static void main(String[] s) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter Name");
        String name = sc.next();
        CheckName ck = new CheckName();
        try {
            ck.validateName(name);
        } catch (InvalidNameException e) {
            System.out.println("Invalid Name " + e);
        }
    }
}

Output

 
D:\Test Java>javac CheckName.java
D:\Test Java>java CheckName
Enter Name
Manish
Invalid Name InvalidNameException: Not a valid name
D:\Test Java>java CheckName
Enter Name
Ram
Valid Name

write a java program to validate the full name of an employee. create and throw a user defined exception if firstname and lastname is blank.

or

write a java program to validate the full name of an employee using exception

import java.util.Scanner;


class Employee{
	private String fname;
	private String lname;
    
   public String getFname(){
          return fname;
   }
   public String getLname(){
          return lname;
   } 
   public void setFname(String fname){
        this.fname=fname;
   } 
   public void setLname(String lname){
        this.lname=lname;
   } 
	
	
}	


class InvalidNameException extends Exception {
    InvalidNameException(String s) {
        super(s);
    }
}	
public class EmployeeName {
    void processName(String fname, String lname) throws InvalidNameException {
         if (fname.isEmpty() &&  lname.isEmpty()) {
            throw new InvalidNameException("Employee First and last name missing");
        }     else if(fname.isEmpty()){
            throw new InvalidNameException("Employee First name is missing");
        }
         else  if(lname.isEmpty()){
            throw new InvalidNameException("Employee Last name is missing");
        }
    }
    public static void main(String[] s) {
        Employee employee=new Employee();
	    employee.setFname("");
	    employee.setLname("");
	   
        EmployeeName ck = new EmployeeName();
        try {
            ck.processName(employee.getFname(),employee.getLname());
			System.out.println("Employee name is "+employee.getFname()+" "+employee.getLname());
        } catch (InvalidNameException e) {
            System.out.println("Invalid Name " + e.getMessage());
        }
    }
}
 
D:\>javac EmployeeName.java

D:\>java EmployeeName
Invalid Name Employee First and last name missing

How to write custom exception in java?

or

How to create custom exception in java?

or

How to create your own exception in java?

  1. Create a class
  2. Extend Exception class
  3. Create a constructor to show/pass a custom message

Q: accept name and age in console and if the age is less than 17 or greater than 24 ,throw a user defined exception “invalidageexception” with the age entered.

Go up and see invalid age exception in java