File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 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 ("\n Demonstrating 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+
You can’t perform that action at this time.
0 commit comments