1

why checked exceptions are not propagated in the chain ?

public static void m() {
    FileReader file = new FileReader("C:\\test\\a.txt");
    BufferedReader fileInput = new BufferedReader(file);

}
public static void n() {
    m();
}
public static void o() {
    n();
}

public static void main(String[] args) {
    try {
        o();
    }
    catch(Exception e) {
        System.out.println("caught exception");
    }

}

And why all checked exceptions should be handled ?

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
supraja
  • 93
  • 2
  • 11

1 Answers1

1

Because you haven't declared them in the method declaration. Checked exceptions must either be handled in the method where they can occur, or they must be declared to be "thrown" by that method.

Change your code to:

public static void m() throws IOException { // <-- Exception declared to be "thrown"
    FileReader file = new FileReader("C:\\test\\a.txt");
    BufferedReader fileInput = new BufferedReader(file);

}
public static void n() throws IOException {
    m();
}
public static void o() throws IOException {
    n();
}

public static void main(String[] args) {
    try {
        o();
    }
    catch(Exception e) {
        System.out.println("caught exception");
    }

}
Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79