Program to input name and age of a person and throw an user-defined exception, if the entered age is negative - Helpwalaa - Free IT Updates & Opportunities

New Updates

Program to input name and age of a person and throw an user-defined exception, if the entered age is negative

  1. Import java.util.Scanner;
  2.  
  3. class AgeNegativeException extends Exception {
  4. public AgeNegativeException(String msg) {
  5. super(msg);
  6. }
  7. }
  8.  
  9. public class NameAgeExcDemo {
  10.  
  11. public static void main(String[] args) {
  12.  
  13. Scanner s = new Scanner(System.in);
  14. System.out.print("Enter ur name :: ");
  15. String name = s.nextLine();
  16. System.out.print("Enter ur age :: ");
  17. int age = s.nextInt();
  18. try {
  19. if(age < 0)
  20. throw new AgeNegativeException("Age must be greater than 0");
  21. else
  22. System.out.println("Valid age !!!");
  23. }
  24. catch (AgeNegativeException a) {
  25. System.out.println("Caught an exception");
  26. System.out.println(a.getMessage());
  27. }
  28. }
  29.  
  30. }

Most Popular