javaexceptionjavasoundaudioinputstream

Why, when calling a method, does it say that I need to catch an exception when I have already caught it?


I have a class that loops some audio:

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");");}
     }
}

I can compile this method and the compiler does not report any errors (I have tested this with print statements). However, when I try to call the main method of the above class (PlayGameMusic) in another class...

public class RunGame
{
    public static void main(String[] args)
    {
       PlayGameMusic.main(null);
    }
}

...I get this compiler error:

unreported exception java.lang.Exception; must be caught or declared to be thrown

I am catching the possible exceptions and the PlayGameMusic class works when run on its own. Why can't I call it from another class?


Solution

  • You've declared your main in PlayGameMusic to throw Exception. Even if nothing in that method actually throws Exception out of the method, you must catch it or declare it in a calling method, e.g. RunGame.main.

    Because you are catching the exceptions in PlayGameMusic.main, you don't need to declare that it throws anything. In PlayGameMusic, change:

    public static void main(String[] args) throws Exception
    

    to

    public static void main(String[] args)