-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathException1.java
More file actions
65 lines (48 loc) · 2.27 KB
/
Copy pathException1.java
File metadata and controls
65 lines (48 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.util.Scanner;
public class ExceptionHandlingExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char continueFlag;
do {
System.out.println("Enter your choice:");
System.out.println("1. Arithmetic operation");
System.out.println("2. Array access");
int choice = sc.nextInt();
switch (choice) {
case 1:
try {
System.out.println("Enter the number to be divided:");
int num = sc.nextInt();
System.out.println("Enter the divisor:");
int divisor = sc.nextInt();
int result = num / divisor;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Caught an exception: Division by zero is not allowed.");
} finally {
System.out.println("Arithmetic operation ended.");
}
break;
case 2:
try {
int[] array = {1, 2, 3, 4, 5};
System.out.println("Enter the index to access:");
int index = sc.nextInt();
System.out.println("Array element: " + array[index]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught an exception: Invalid array index.");
} finally {
System.out.println("Array access operation ended.");
}
break;
default:
System.out.println("Invalid choice! Please choose 1 or 2.");
break;
}
System.out.println("Do you want to continue? (y/n)");
continueFlag = sc.next().charAt(0);
} while (continueFlag == 'y' || continueFlag == 'Y');
System.out.println("Program has ended.");
sc.close();
}
}