0% found this document useful (0 votes)
4 views2 pages

Experiment 06: Import Public Class Public Static Void New Try

Uploaded by

lomtenavnath28
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Experiment 06: Import Public Class Public Static Void New Try

Uploaded by

lomtenavnath28
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Experiment 06

/*
6.Exception handling: Implement a program to handle Arithmetic exception,
Array Index Out of Bounds. The user enters two numbers Num1 and Num2. The
division of Num1 and Num2 is displayed. If Num1 and Num2 are not integers,
the program would throw a Number Format Exception. If Num2 were zero, the
program would throw an Arithmetic Exception. Display the exception
*/

import java.util.Scanner;

public class ExceptionHandlingExample {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
try {
// Prompt the user to enter two numbers
System.out.print("Enter the first number (Num1): ");
String input1 = scanner.nextLine();
System.out.print("Enter the second number (Num2): ");
String input2 = scanner.nextLine();

// Attempt to parse the inputs as integers


int num1 = Integer.parseInt(input1);
int num2 = Integer.parseInt(input2);

// Perform division
int result = num1 / num2;
System.out.println("Result of division (Num1 / Num2): " +
result);

// Simulate Array Index Out of Bounds for demonstration


int[] array = new int[5];
System.out.println("Accessing an out-of-bounds index: " +
array[10]);

} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception: Division by zero is
not allowed.");
} catch (NumberFormatException e) {
System.out.println("Number Format Exception: Please enter valid
integers.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out of Bounds Exception: Tried
to access an invalid array index.");
} finally {
scanner.close();
System.out.println("Program execution completed.");
}
}
}

Output:

//Test 1
Enter the first number (Num1): 10
Enter the second number (Num2): 0
Arithmetic Exception: Division by zero is not allowed. Program
execution completed.

//Test 2
Enter the first number (Num1): ten
Enter the second number (Num2): five
Number Format Exception: Please enter valid integers. Program
execution completed.

//Test 3
Enter the first number (Num1): 10
Enter the second number (Num2): 2
Result of division (Num1 / Num2): 5
Array Index Out of Bounds Exception: Tried to access an invalid array
index. Program execution completed.

You might also like