0

I'm reading Java from HeadFirst. I started reading the chapter about Exception Handling. There was code in the book that I executed on my computer.

import javax.sound.midi.*;
class PlayMusic
{
    public void play()
    {
        try{
            Sequencer sq = MidiSystem.getSequencer();
            System.out.println("We got a sequencer");
        }
        catch(MidiUnavailableException ex)
        {   
            System.out.println("Bummer!");  
            ex.printStackTrace();
        }
    }
    public static void main(String[] args)
    {
        PlayMusic pm = new PlayMusic();
        pm.play();
    }
}

When I remove the try-catch block, the compiler raises a MidiUnavailableException error. I used try-catch to catch that exception, but System.out.println("Bummer"); doesn't get executed. Instead, the try block is executed.

What is happening here?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Arindam
  • 163
  • 1
  • 13
  • You should keep reading or read [this tutorial](https://docs.oracle.com/javase/tutorial/essential/exceptions/try.html). The `catch` block is only execute iff. a fitting `Exception` is raised. The compiler did complain because you did not catch the exception at all (the compiler cannot possbile know if an `Exception` is raised at execution time). – Turing85 Oct 13 '16 at 22:29

2 Answers2

1

When you get a compiler error, it means the method may throw an MidiUnavailableException. At runtime is when exceptions are thrown, and if the action succeeds then the catch block will not be entered. If you have a finally block, that is guaranteed to be entered.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

MidiUnavailableException is a checked exception, so you are required to include the catch block in order for the code to compile. However, there is no guarantee that the exception will actually be thrown when your program executes. In your case, it isn't being thrown, so the code in your try block executes normally and your printout for the error never gets called.

Todd Dunlap
  • 141
  • 6
  • So, you mean that whenever I'll use `getSequencer()` method, I need to enclose it within try-catch block, because it might raise an `Exception`. – Arindam Oct 13 '16 at 22:38
  • Yes, either that or declare that the enclosing method throws the exception (in this case, the "play" method). – Todd Dunlap Oct 13 '16 at 22:45