How to put `throws IOException` to the statement

牧云@^-^@ 提交于 2020-01-16 08:04:38

问题


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?


回答1:


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.




回答2:


You need to add throws IOException to the declaration of HighestScoreFile




回答3:


you code try to throw another error rather than IOException, and you did not catch it.




回答4:


The error message says it all: the called method may throw an IOException, which must be caught or declared to be thrown.

So either you wrap the call in a try-catch block, or you declare that the caller method throws IOException too.




回答5:


You have to either declare the exception as thrown in your method (throws IOException in the method in your new java file) or surround it with a try / catch block



来源:https://stackoverflow.com/questions/10618722/how-to-put-throws-ioexception-to-the-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!