Nat*_*ahn 0 java exception javasound audioinputstream
我有一个循环一些音频的类:
public class PlayGameMusic {
public static void main(String[] args) throws Exception {
try{
AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File("\\Users\\natal\\Desktop\\programs\\APCS\\Fill the Boxes.wav"));
Clip clip = AudioSystem.getClip();
clip.open(inputStream);
clip.loop(Clip.LOOP_CONTINUOUSLY);
Thread.sleep(10000);
}
catch(IOException error){System.out.println("IO Exception Error");}
catch(InterruptedException error){System.out.println("InterruptedException");}
catch(Exception error){System.out.print("System.out.println("Exception");");}
}
}
Run Code Online (Sandbox Code Playgroud)
我可以编译这个方法,并且编译器不会报告任何错误(我已经使用print语句对其进行了测试).但是,当我尝试PlayGameMusic在另一个类中调用上面的class()的main方法时......
public class RunGame
{
public static void main(String[] args)
{
PlayGameMusic.main(null);
}
}
Run Code Online (Sandbox Code Playgroud)
...我得到这个编译器错误:
Run Code Online (Sandbox Code Playgroud)unreported exception java.lang.Exception; must be caught or declared to be thrown
我正在捕捉可能的异常,并且PlayGameMusic该类在单独运行时有效.为什么我不能从另一个班级打电话呢?
你宣布你main的PlayGameMusic投掷Exception.即使该方法中没有任何内容实际抛出Exception该方法,您必须捕获它或在调用方法中声明它,例如RunGame.main.
因为您正在捕获异常PlayGameMusic.main,所以您不需要声明它会抛出任何内容.在PlayGameMusic,改变:
public static void main(String[] args) throws Exception
Run Code Online (Sandbox Code Playgroud)
至
public static void main(String[] args)
Run Code Online (Sandbox Code Playgroud)