Tuesday, 4 March 2025

Write a java program to accept Employee name from the user and check whether it is valid or not. If it is not valid then throw user defined Exception “Name is Invalid” otherwise display it.



import java.io.*;


// Custom exception for invalid names

class InvalidNameException extends Exception {

    InvalidNameException(String msg) {

        super(msg);

    }

}


class Employee {

    String name;


    Employee(String name) {

        this.name = name;

    }


    void display() {

        System.out.println("Employee Name: " + name);

    }


    public static void main(String args[]) throws Exception {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));


        System.out.print("Enter Employee Name: ");

        String name = br.readLine().trim(); // Trim spaces to remove accidental spaces


        try {

            // Validate the name

            for (int i = 0; i < name.length(); i++) {

                char ch = name.charAt(i);

                if (!Character.isLetter(ch) && ch != ' ') {

                    throw new InvalidNameException("Name contains invalid characters!");

                }

            }


            // If valid, create an Employee object and display the name

            Employee emp = new Employee(name);

            emp.display();

        } catch (InvalidNameException e) {

            System.out.println("Error: " + e.getMessage());

        }

    }

}