0

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    What does this do: `public static void main(String[] args) throws Exception {`, the `throws Exception` part? – Hovercraft Full Of Eels Jun 08 '18 at 00:27
  • Sorry but this cannot compile: catch(Exception error){System.out.print("System.out.println("Exception");");} – lohnns Jun 08 '18 at 00:38
  • `catch(IOException error){System.out.println("IO Exception Error");}` BTW - that should logically be `catch(IOException error){System.err.println("IO Exception Error");}` or even better (and shorter) `catch(IOException error){error.printStackTrace();}` – Andrew Thompson Jun 08 '18 at 10:08

3 Answers3

6

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)
rgettman
  • 176,041
  • 30
  • 275
  • 357
1

If a method calls another method which explicitly throws Exception, then the calling method should catch that Exception or declared it to be thrown in its own method signature

https://docs.oracle.com/cd/A97339_01/doc/bc4j/BC4JRuntimeFiles/obcExceptions.htm

Joe Manavalan
  • 103
  • 1
  • 5
0

If PlayGameMusic.main can't throw Exception it shouldn't be declared with throw Exception. It shouldn't have throw Exception just because it can generate and catch Exception.

Erik Levin
  • 47
  • 1
  • 4