基本上,我正在尝试在Robocode中生成一个日志文件,但我遇到了问题,因为你不能在Robocode中使用try / catch(据我所知)。我做了以下事情:
public void onBattleEnded(BattleEndedEvent e) throws IOException
{
writeToLog();
throw new IOException();
}
和
public void writeToLog() throws IOException
{
//Create a new RobocodeFileWriter.
RobocodeFileWriter fileWriter = new RobocodeFileWriter("./logs/test.txt");
for (String line : outputLog)
{
fileWriter.write(line);
fileWriter.write(System.getProperty("line.seperator"));
}
throw new IOException();
}
并在编译时遇到以下错误: -
MyRobot.java:123: onBattleEnded(robocode.BattleEndedEvent) in ma001jh.MyRobot cannot implement onBattleEnded(robocode.BattleEndedEvent) in robocode.robotinterfaces.IBasicEvents2; overridden method does not throw java.io.IOException
public void onBattleEnded(BattleEndedEvent e) throws IOException
^
1 error
答案 0 :(得分:1)
如您所见here,接口不会声明任何已检查的异常。所以你不能在实现类中抛出一个。
解决此问题的一种方法是实现这样的方法:
public void onBattleEnded(BattleEndedEvent e)
{
writeToLog();
throw new RuntimeException(new IOException());
}
public void writeToLog()
{
//Create a new RobocodeFileWriter.
RobocodeFileWriter fileWriter = new RobocodeFileWriter("./logs/test.txt");
for (String line : outputLog)
{
fileWriter.write(line);
fileWriter.write(System.getProperty("line.seperator"));
}
throw new new RuntimeException(new IOException());
}
答案 1 :(得分:1)
但我遇到了问题,因为你不能在Robocode中使用try / catch(据我所知)
这个假设来自哪里?我只是因为你的问题在这里安装了robocode(所以如果我将来不经常回答这是你的错),写了我自己的机器人,它可以很好地捕捉异常:
try {
int i = 1/0;
}
catch(ArithmeticException ex) {
ex.printStackTrace();
}
为什么要在你的例子中抛出IOExceptions?