-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample1.java
More file actions
52 lines (45 loc) · 1.99 KB
/
Copy pathExample1.java
File metadata and controls
52 lines (45 loc) · 1.99 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
import java.util.Scanner;
public class Example1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Handle Divide by Zero
try {
System.out.print("Enter a number to divide: ");
int num1 = scanner.nextInt();
System.out.print("Enter a number to divide by: ");
int num2 = scanner.nextInt();
int result = num1 / num2; // This may throw ArithmeticException if num2 is 0
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
}
// Handle Array Index Out of Bounds
try {
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
int[] arr = new int[size];
System.out.print("Enter the index to access in the array: ");
int index = scanner.nextInt();
System.out.println("Value at index " + index + ": " + arr[index]); // This may throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Array index is out of bounds.");
}
// Handle Number Format
try {
System.out.print("Enter a number (without decimal): ");
String input = scanner.next();
int num = Integer.parseInt(input); // This may throw NumberFormatException if input is not a valid number
System.out.println("Parsed number: " + num);
} catch (NumberFormatException e) {
System.out.println("Error: Invalid number format.");
}
// Handle Null Pointer
try {
String str = null;
System.out.println("Length of string: " + str.length()); // This will throw NullPointerException
} catch (NullPointerException e) {
System.out.println("Error: Null pointer exception.");
}
scanner.close();
}
}