-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExceptionDemo.java
More file actions
40 lines (36 loc) · 1.4 KB
/
ExceptionDemo.java
File metadata and controls
40 lines (36 loc) · 1.4 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
import java.io.*;
public class ExceptionDemo {
public static void main(String[] args) {
// a) Arithmetic Exception
try {
int result = 10 / 0;
// Attempting to divide by zero
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: Attempt to divide by zero");
e.printStackTrace();
}
// b) Number Format Exception
try {
String str = "abc";
int num = Integer.parseInt(str);
} catch (NumberFormatException e) {
System.out.println("NumberFormatException caught: Input is not a valid integer");
e.printStackTrace();
}
// c) Array Index Out of Bound Exception
try {
int[] arr = new int[5];
arr[10] = 50; // Accessing an index beyond the size of the array
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught: Index is out of bounds");
e.printStackTrace();
}
// d) Negative Array Size Exception
try {
int[] negativeArray = new int[-5]; // Cannot create an array with negative size
} catch (NegativeArraySizeException e) {
System.out.println("NegativeArraySizeException caught: Cannot create an array with negative size");
e.printStackTrace();
}
}
}