Skip to content

Commit 980daca

Browse files
committed
program 4.3
1 parent f135a9b commit 980daca

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

ucer/4B4/4_3.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import java.io.*;
2+
3+
class ExceptionDemo {
4+
5+
// Method demonstrating a checked exception
6+
public static void readFile(String fileName) throws IOException {
7+
FileReader file = new FileReader(fileName); // may throw FileNotFoundException
8+
BufferedReader fileInput = new BufferedReader(file);
9+
10+
System.out.println("Reading first line from file:");
11+
System.out.println(fileInput.readLine());
12+
13+
fileInput.close();
14+
}
15+
16+
// Method demonstrating an unchecked exception
17+
public static void divide(int a, int b) {
18+
int result = a / b; // may throw ArithmeticException
19+
System.out.println("Result: " + result);
20+
}
21+
22+
public static void main(String[] args) {
23+
// Handling unchecked exception
24+
try {
25+
System.out.println("Demonstrating Unchecked Exception:");
26+
divide(10, 0); // division by zero
27+
} catch (ArithmeticException e) {
28+
System.out.println("Caught an unchecked exception: " + e);
29+
}
30+
31+
// Handling checked exception
32+
try {
33+
System.out.println("\nDemonstrating Checked Exception:");
34+
readFile("nonexistentfile.txt"); // file may not exist
35+
} catch (IOException e) {
36+
System.out.println("Caught a checked exception: " + e);
37+
}
38+
}
39+
}
40+

0 commit comments

Comments
 (0)