2011-03-05 58 views
1

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

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

我也想看看界面。你是否只导入了'java.io.IOException'而不是别的? – adarshr 2011-03-05 14:15:58

+0

是的,我只输入那个。 – 2011-03-05 14:21:20

回答

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()); 
} 
+0

请参阅其中的问题;如果我把它拿走,编译器会给出一个错误,说明基本上必须捕获或声明异常。 – 2011-03-05 14:22:16

+0

然后声明为'抛出RuntimeException' – adarshr 2011-03-05 14:23:48

+0

谢谢你,因为你可能会告诉我,我相对较新的Java,并且对异常处理非常新。无论如何,所以我声明为“抛出RuntimeException”,编译器仍然希望我捕获或声明IOException。我试图使用'抛出新的RuntimeException',但那不行。谢谢。 – 2011-03-05 14:39:13

1

,但我有问题,因为你不能在Robocode的使用try/catch语句(据我所知)

这个假设从何而来?我是你的问题在这里安装的robocode只是因为(所以它是你的错,如果我会回答这里不常在未来的),写我自己的机器人,它可以捕获异常相当不错:

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

而且你为什么扔IOException在你的例子?

+0

是的,很抱歉,我对与robocode有关异常处理方面的限制有些混淆。我试图将其作为试用/错误场景的一部分。毕竟我是一名新的CS学生,必须犯错误。 – 2011-03-13 15:16:41