In: Computer Science
Develop a Java program that prompts the user to enter her birth year (e.g. 1980). The program then uses the current year (i.e. 2020) and displays age of the user (i.e. 40). The program should handle any exception that can occur due to the value entered by the user.
//Program to calculate the age
import java.util.Scanner; //importing scanner class for taking
input
public class Main //Main class
{
   public static void main(String[] args) { //Main
method
   int x=0,age,currentYear=2020; //initialising
variables
   Scanner input= new Scanner(System.in);
       System.out.print("Enter the year of
Birth: ");   
       try{ //taking input under try block
to handle Exception
       x=input.nextInt(); //taking input
from User
       }
       catch(Exception
InputMismatchException){ //handling Exception by catch
       System.out.println("\n Invalid
Input by User!!");
       System.exit(0); //exiting
program
       }
       if (x>currentYear){ //this will
handle if year of birth entered is greaterthen currentYear
       System.out.println("Year of birth
cannot be greater than "+currentYear);
       System.exit(0); //exiting
program
       }
       age=currentYear-x; //calculating
age
       if(age==0){ //if year of birth is
currentYear
       System.out.println("Age is under 1
year");
       }
       else{
       System.out.println("Age is: "+age);
//Showing age
       }
  
   }
}
coding and output screen:

OUTPUT:


