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

75 Views Asked by At

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?

3

There are 3 best solutions below

0
On BEST ANSWER

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)
0
On

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.

0
On

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