Day 12 - 26 August, 2024

Program 34 : WAP to create a program to understand the concept of Exception Handling

import java.util.*; class P34 { public static void main(String[] args) { int x,y,z; Scanner sc = new Scanner(System.in); try { System.out.println("----------------------------"); System.out.print("Enter the first Number : "); x = sc.nextInt(); System.out.print("Enter the Second Number : "); y = sc.nextInt(); System.out.println("----------------------------"); z = x/y; System.out.println("the Division is : " + z); System.out.println("----------------------------"); } catch(ArithmeticException ex1) { System.out.println("Are you trying to / by zero?"); System.out.println("the error is : " + ex1); System.out.println("----------------------------"); } catch(InputMismatchException ex2) { System.out.println("Enter Numbers only."); System.out.println("the error is : " + ex2); System.out.println("----------------------------"); } finally { System.out.println("This is finally Block"); System.out.println("----------------------------"); } } } Copy Code
Expected Output: Scenario 1: Division by Zero
----------------------------
Enter the first Number : 10
Enter the Second Number : 0
----------------------------
Are you trying to / by zero?
the error is : java.lang.ArithmeticException: / by zero
----------------------------
This is finally Block
----------------------------
Expected Output: Scenario 2: Invalid Input (Non-Integer)
----------------------------
Enter the first Number : 10
Enter the Second Number : abc
----------------------------
Enter Numbers only.
the error is : java.util.InputMismatchException
----------------------------
This is finally Block
----------------------------

Program 35 : WAP to create a program to understand the concept of Exception Handling and Input through BufferedReader

import java.io.*; class P35 { public static void main(String[] args) throws IOException { int empid; String empname; double salary; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("----------------------------"); System.out.print("Enter Employee ID : "); empid = Integer.parseInt(br.readLine()); System.out.print("Enter Employee Name : "); empname = br.readLine(); System.out.print("Enter Employee Salary : "); salary = Double.parseDouble(br.readLine()); System.out.println("----------------------------"); System.out.println("Employee Name : " + empname); System.out.println("Employee ID : " + empid); System.out.println("Employee Salary : " + salary); System.out.println("----------------------------"); } } Copy Code
Expected Output:
----------------------------
Enter Employee ID : 101
Enter Employee Name : Hardik Srivastava
Enter Employee Salary : 50000.75
----------------------------
Employee Name : John Doe
Employee ID : 101
Employee Salary : 50000.75
----------------------------