exceptionjdom

multiple catch clauses with each having its own message box


could someone tell me why only the messagebox in the catch clause FileNotFoundException shows up even when the exception was an IO- or JDOMException? why does java ignore the relevant message boxes in these catch clauses? thx!

public void SetWurzel() {
    builder = new SAXBuilder();
    xmlFile = new File(Pfad);
    try {
        document = (Document) builder.build(xmlFile);
    } catch (FileNotFoundException e) {
        JOptionPane
                .showMessageDialog(
                        null,
                        "Die Datei konnte nicht gefunden werden. Bitte überprüfen Sie den Pfad"
                                + " auf Korrektheit.");
    } catch (IOException e) {
        JOptionPane
                .showMessageDialog(
                        null,
                        "Bitte prüfen Sie die Zugriffsrechte auf Ihre Datei und geben "
                                + "Sie diese gegebenenfalls frei. ");
    } catch (JDOMException e) {
        JOptionPane
                .showMessageDialog(
                        null,
                        "Bitte Prüfen Sie die Struktur der einzulesenden XMLDatei auf Fehlern"
                                + " und fehlende Elemente.");
    }
    Wurzel = document.getRootElement();
}

Solution

  • FileNotFoundException is, in fact, an IOException (it's a subclass). So, because you specify the FileNotFound catch block first, if the file is not found, and that exception is thrown, it is caught first.

    Once the exception is handled by that catch block, the try/catch block completes,and your code moves on.

    Note that catch blocks do not 'cascade'.... completing the first catch block does not make the next one start..... Only the first catch block that can handle the exception is executed.

    So, if there's an IOException that's not a FileNot found, the second catch block will run.

    If there's an exception in the XML parsing, or with the structure of the document, then the JDOMException handler will run.

    Only one of them will run when there's an exception... that's the way Java works.