Search code examples
javaioioexception

How to put `throws IOException` to the statement


I am trying to implement a class from HighestScoreFile.java and when I compile, I get this error :

...MemoryGame.java:211: error: unreported exception IOException; must be caught or declared to be thrown
                    HighestScoreFile.HighestScoreFile(input, hours, minutes, seconds, click);
                                                     ^
1 error

Before I implement this HighestScoreFile.java, I have tested with a main class using

public static void main(String[] args) throws IOException
    {
        HighestScoreFile("abcdefg", 12, 13, 14, 30);
    }

The HighestScoreFile.java is used to save the data into a Highest.txt.

But when I implement to another .java using the code below, it shows out that error.

HighestScoreFile.HighestScoreFile(input, hours, minutes, seconds, click);

How can I fix this problem?


Solution

  • You need to either throw the exception outside of the method:

    public void someMethod() throws IOException
    {
        // ...
        HighestScoreFile.HighestScoreFile(input, hours, minutes, seconds, click);
        // ..
    }
    

    Or catch the excetion:

    try 
    {
        HighestScoreFile.HighestScoreFile(input, hours, minutes, seconds, click);
    }
    catch (IOException ex)
    {
        // handle the exception
    }
    

    I suggest you follow the Java exception trail.