Answer to Question #235999 in Java | JSP | JSF for jerry

Question #235999

Write a java program to throw an exception (checked) for an employee

details

a If an employee name is a number, a name exception must be

thrown

b If an employee age is greater than 50, an age exception must be

thrown. Or else an object must be created for the entered employee details.


1
Expert's answer
2021-09-13T12:19:03-0400
public class NameException extends Exception {
    public NameException() {
        super("The name cannot be an integer.");
    }

    public NameException(String message) {
        super(message);
    }
}


public class AgeException extends Exception{
    public AgeException() {
        super("Age is too high.");
    }

    public AgeException(String message) {
        super(message);
    }
}


public class Employee {
    private String name;
    private int age;

    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}


import java.util.Scanner;

public class Main {

    public static Employee createEmployee(String name, int age) throws NameException, AgeException {
        if (age > 50) {
            throw new AgeException();
        }
        try {
            Double.parseDouble(name);
            throw new NameException();
        } catch (NumberFormatException e) {
        }
        return new Employee(name, age);
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String name = in.nextLine();
        int age = Integer.parseInt(in.nextLine());
        try {
            createEmployee(name,age);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS