try(FileInputStream fis = (new FileInputStream("*FILE*"))){
Player player = new Player(fis);
Button btn = new Button();
btn.setText("Start");
Button btn2 = new Button();
btn2.setText("Stop");
}catch(JavaLayerException | IOException e ){
e.printStackTrace();
}
btn.setOnAction((ActionEvent event) -> {
this.player = player;
try{
new playMusic(player).start();
}catch(Exception e){
e.printStackTrace();
}
});
btn2.setOnAction((ActionEvent event)->{
player.close();
});
答案 0 :(得分:1)
将代码移动到访问try
块内的变量,或者在try
块外声明变量,并确保在注册事件处理程序时将其初始化。
final Player player;
try(FileInputStream fis = new FileInputStream("*FILE*")){
player = new Player(fis);
} catch(JavaLayerException | IOException e){
e.printStackTrace();
// prevent access to uninitialized player variable by exiting the method
throw new RuntimeException(e);
}
Button btn = new Button();
btn.setText("Start");
Button btn2 = new Button();
btn2.setText("Stop");
btn.setOnAction((ActionEvent event) -> {
this.player = player;
try{
new playMusic(player).start();
} catch(Exception e){
e.printStackTrace();
}
});
btn2.setOnAction((ActionEvent event)->{
player.close();
});
代替
throw new RuntimeException(e);
您也可以使用
正常退出该方法return;
相反。
如果Player
没有读取构造函数中的所有代码,则不能关闭它。 try-with-resources可以做到这一点。更改为try
catch
try {
FileInputStream fis = new FileInputStream("*FILE*");
try {
player = new Player(fis);
} catch(JavaLayerException | IOException e) {
e.printStackTrace();
fis.close(); // close stream on player creation failure
// prevent access to uninitialized player variable by exiting the method
throw new RuntimeException(e);
}
} catch(IOException e){
e.printStackTrace();
// prevent access to uninitialized player variable by exiting the method
throw new RuntimeException(e);
}