User Defined Exception in Java

Sometimes for our programming requirements, we need to create our exceptions, such types of exceptions are known as user-defined exceptions or customized exceptions.

For Example-

If the user is less than 18, the user is not illegal for voting, so we can create our exception NotAllowedException.

package UserDefine;

import java.util.Scanner;

class NotAllowedException extends RuntimeException
{
    NotAllowedException(String e){
        System.out.println(e);
    }

}
public class UserDefinedException{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your age");
        int age = sc.nextInt();
        if(age<18){
            throw new  NotAllowedException(" You're not eligible for voting");
        }
        else {
            System.out.println("You're eligible for voting");
        }
    }

}
User Defined Exception in Java

Note-

  • Throw keyword is best suitable for user-defined or customized exceptions.
  • It is highly recommended to define customized exceptions as unchecked exceptions that is we have to extend RunTimeException

Similar Java Tutorials

5 thoughts on “User Defined Exception in Java”

Leave a Comment