【问题标题】:Why exception occurs in this program?为什么这个程序会出现异常?
【发布时间】:2015-12-09 02:04:45
【问题描述】:

我有这个程序,并且总是在输出中将 try catch 块中的异常作为“错误”。为什么输出会跳到catch?代码如下:

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

class pgm {
  public static void main(String[] args) {
    StringBuffer sa = new StringBuffer();
    StringBuffer n = new StringBuffer();
    StringBuffer sb = new StringBuffer();

    try {
      FileReader fr = new FileReader("1.txt");
      int i;

      while ((i = fr.read()) != -1) {
        n.append((char) i);
      }
      fr.close();
    } catch (Exception e) {
    }

    String[] lines = String.valueOf(n).split("\n");

    int x = lines.length;
    int count = 1, m = 0;

    try {
      FileWriter fw1 = new FileWriter("1a.txt");
      FileWriter fw2 = new FileWriter("1b.txt");

      String linea = Files.readAllLines(Paths.get("1.txt")).get(1);
      sa.append(linea);

      for (int i = 2; count <= x; i++) {
        String lineb = Files.readAllLines(Paths.get("1.txt")).get(count);
        String ab = lineb;
        ab = ab.replace("\n", "");
        count++;
        String linec = Files.readAllLines(Paths.get("1.txt")).get(count);
        ab += linec;
        sb.append(ab);
        count++;
        m = 0;

        for (int j = 0; j < 5; j++) {
          String lined = Files.readAllLines(Paths.get("1.txt")).get(count);
          if (lined == "\n") {
            count++;
            m++;
          } else {
            break;
          }
        }

        for (int j = 0; j < m; j++) {
          sa.append("\n");
          sb.append("\n");
        }

        String linee = Files.readAllLines(Paths.get("1.txt")).get(count);
        sa.append(linee);
      }

      String sa1 = String.valueOf(sa);
      String sa2 = String.valueOf(sb);

      fw1.write(sa1);
      fw2.write(sa2);
      fw1.close();
      fw2.close();
    } catch (Exception e) {
      System.out.println("Something wrong");
    }
  }
}

究竟是什么导致了 catch 块中的异常?

【问题讨论】:

  • 在catch块中添加e.printStackTrace(),你就知道了。
  • 请不要使用StringBuffer,因为它在十多年前就被StringBuilder取代了。
  • 如果你想知道它为什么会产生错误,也许你不应该丢弃你的异常,就好像它们没有发生一样。
  • 读一个文件很贵,我建议你读一次文件,而且只读一次。您正在以疯狂的次数阅读整个文件,在多行代码中使用两种不同的方式。
  • 顺便说一句,List 的第一个索引是 0 而不是 1

标签: java exception-handling


【解决方案1】:

是的,如果您不打算处理或重新抛出异常,则不应捕获它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多