首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Robocode (Java)中的文件编写

Robocode (Java)中的文件编写
EN

Stack Overflow用户
提问于 2011-03-05 22:12:16
回答 2查看 2K关注 0票数 3

基本上,我正在尝试在Robocode中生成一个日志文件,但我遇到了一些问题,因为你不能在Robocode中使用try/catch (据我所知)。我做了以下工作:

代码语言:javascript
复制
public void onBattleEnded(BattleEndedEvent e) throws IOException
{
    writeToLog();
    throw new IOException();
}

代码语言:javascript
复制
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();
}

并且我在编译时得到以下错误:-

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-03-05 22:17:59

正如您所看到的here,该接口没有声明任何检查过的异常。所以你不能在你的实现类中抛出一个。

解决这个问题的一种方法是像这样实现你的方法:

代码语言:javascript
复制
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());
}
票数 2
EN

Stack Overflow用户

发布于 2011-03-06 10:53:10

但是我遇到了一些问题,因为你不能在Robocode中使用try/catch (据我所知)

这个假设是从哪里来的?我只是因为你的问题在这里安装了机器人代码(所以如果我以后不经常在这里回答是你的错),写了我自己的机器人,它可以很好地捕捉异常:

代码语言:javascript
复制
try {
   int i = 1/0;
}
catch(ArithmeticException ex) {
   ex.printStackTrace();
}

为什么在你的例子中使用IOExceptions呢?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5204304

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档