用Robocode(Java)编写文件

用Robocode(Java)编写文件,java,file,robocode,Java,File,Robocode,基本上,我试图在Robocode中生成一个日志文件,但我遇到了一些问题,因为您无法在Robocode中使用try/catch(据我所知)。我已经做了以下工作: public void onBattleEnded(BattleEndedEvent e) throws IOException { writeToLog(); throw new IOException(); } 及 我在编译时遇到以下错误:- MyRobot.java:123: onBattleEnded(roboc

基本上,我试图在Robocode中生成一个日志文件,但我遇到了一些问题,因为您无法在Robocode中使用try/catch(据我所知)。我已经做了以下工作:

public void onBattleEnded(BattleEndedEvent e) throws IOException
{
    writeToLog();
    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
如您所见,接口没有声明任何已检查的异常。所以你不能在你的实现类中抛出一个

解决此问题的一种方法是实现如下方法:

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());
}
但我有一些问题,因为你不能在机器人代码中使用try/catch(据我所知)

这一假设从何而来?我只是因为你的问题在这里安装了robocode(因此,如果我以后在这里回答的次数较少,这是你的错),我自己写了一个机器人,它可以很好地捕捉异常:

try {
   int i = 1/0;
}
catch(ArithmeticException ex) {
   ex.printStackTrace();
}

为什么要在示例中抛出IOException?

我也想看看接口。你只导入了
java.io.IOException
而没有导入其他东西吗?是的,我只导入了它。看,这就是问题所在;如果我把它拿走,编译器会给出一个错误,基本上说异常必须被捕获或声明。然后declare as
抛出RuntimeException
谢谢,你可能会发现我对Java比较陌生,对异常处理非常陌生。无论如何,我声明为
抛出RuntimeException
,编译器仍然希望我捕获或声明
IOException
。我尝试使用
抛出新的RuntimeException
,但这不起作用。谢谢。你能给我看看界面的内容吗?我觉得我错过了一些重要的事情。对不起,你这到底是什么意思。对不起,我对整个Java都不熟悉。谢谢。是的,很抱歉,我对robocode places在异常处理方面的限制有点困惑。我试着将其作为试错方案的一部分。我毕竟是一名CS新生,必须犯错误。
try {
   int i = 1/0;
}
catch(ArithmeticException ex) {
   ex.printStackTrace();
}