简体   繁体   中英

Java try/catch block not outputting text when exception is caught

I've been going through the Head First Java 2E book, which covers Java 5, and I'm running into an issue with exception handling that I don't understand. In the exceptional handling chapter, the book gives the following example as the correct way to use a try/catch block to catch a MidiUnavailableException.

import javax.sound.midi.*;

public class MusicTest {

    public void play() {
        try {
            Sequencer sequencer = MidiSystem.getSequencer();
            System.out.println("Sequencer initialized...");
        } catch (MidiUnavailableException ex) {
            System.out.println("Bummer...");
        }
    }

    public static void main(String[] args) {
        MusicTest mt = new MusicTest();
        mt.play();
   }

}

Without the try/catch block, the program fails to compile with a MidiUnavailableException. I would expect that with the code above, I would get the output:

Bummer...

instead, I get

Sequencer initialized...

Is this just a difference between Java 5 and Java 8 or am I doing something incorrectly?

I'll try to keep it short.

Try/catch block handles an exception IF there is one.

BUT on some cases, you HAVE to put a try/catch block in order to use a class that MAY throw an exception.

So in your case if you take it out, your code won't compile because it is asking for the try/catch block, that doesn't mean there will always be an exception.

Hope this helps.

The Sequencer Class may throw an exception. That's why you have to add the try catch blocks. But it runs fine so no exceptions are thrown.

Try to remove your device and then run it. It probably will then throw the exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM