java - 为什么我收到错误 "must be caught or declared to be thrown"?

标签 java for-loop

import java.io.*;

public class prelab7 {

   public static void readstring(String a){

    String s = "EECS 132";

    StringReader s1 = new StringReader(s);
    for (int n = 0; n < s.length(); n = n + 1){

        char c = (char)s1. read();
        System.out.print(" " + c);
    }
  }
}

发现 1 个错误: 文件:/Users/clara/Desktop/EECS132/prelab7.java [行:8] 错误:/Users/clara/Desktop/EECS132/prelab7.java:8:未报告的异常 java.io.IOException;必须被捕获或宣布被抛出

最佳答案

StringReader 是一个Reader。以及 Reader.read() 方法 can throw an IOException .

您需要将方法声明更改为:

public static void readstring(String a)
    throws IOException
{
    // code here
}

(编辑:或使用 try/catch,如评论中所述;但是,如果您这样做,请避免使用经典的 .printStackTrace() )

关于java - 为什么我收到错误 "must be caught or declared to be thrown"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22029790/

相关文章:

java - 测试调用 : how to do set up common to all test suites

java - 如何在 IE 中打开 wsdl 文件

java - Java 接口(interface)中的公共(public)/私有(private)方法签名

mysql - 使用sql变量生成范围内的表

python - for循环迭代元组

python - 为什么我的 for 循环打印在每隔一行而不是每一行?

java - Netbeans 7.3 的 RTF 副本

java - 如何重命名结果程序集以安装在 .m2 中

c - 为什么打印 012 而不是 123

php - 在 MySQL 中每年插入 52 周(PHP 脚本)