Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>EJP is correct above in that your mLine variable is scoped only to the try block. (I had to run it in the debugger myself before it made sense to me. Syntax highlighting helped afterwards, coloring my instance variable different than the local variable.) The mLine you return is actually the instance variable.</p> <pre><code> try { SourceDataLine mLine = (SourceDataLine) AudioSystem.getLine(info); /** * if that succeeded, try opening the line. */ mLine.open(audioFormat); /** * And if that succeed, start the line. */ mLine.start(); } catch (LineUnavailableException e) { throw new RuntimeException("could not open audio line"); } return mLine; </code></pre> <p>Is essentially the same as:</p> <pre><code> try { SourceDataLine mLine = (SourceDataLine) AudioSystem.getLine(info); /** * if that succeeded, try opening the line. */ mLine.open(audioFormat); /** * And if that succeed, start the line. */ mLine.start(); } catch (LineUnavailableException e) { throw new RuntimeException("could not open audio line"); } return this.mLine; </code></pre> <p>because the return mLine is outside the try block that it was declared in. In practice re-using the name of an instance variable as a local variable is not safe for this very reason. If you attempt to rename the variable to something like "line" using the refactoring tool in an IDE like Eclipse or Idea then it will only rename the references in the try scope further highlighting your bug.</p> <pre><code> try { SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info); /** * if that succeeded, try opening the line. */ line.open(audioFormat); /** * And if that succeed, start the line. */ line.start(); } catch (LineUnavailableException e) { throw new RuntimeException("could not open audio line"); } return mLine; </code></pre> <p>If you then try to manually re-key the reference in the return statement you will get a compile error.</p> <pre><code> try { SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info); /** * if that succeeded, try opening the line. */ line.open(audioFormat); /** * And if that succeed, start the line. */ line.start(); } catch (LineUnavailableException e) { throw new RuntimeException("could not open audio line"); } return line; //Will not compile! </code></pre> <p>The proper fix is to tuck the return statement inside the try block:</p> <pre><code> try { SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info); /** * if that succeeded, try opening the line. */ line.open(audioFormat); /** * And if that succeed, start the line. */ line.start(); return line; } catch (LineUnavailableException e) { throw new RuntimeException("could not open audio line"); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload