2015-09-12 92 views
-6

我有這個程序,並且總是在try catch塊中得到輸出中「Something Wrong」的異常。爲什麼輸出跳到捕捉?這裏是代碼:爲什麼在這個程序中發生異常?

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塊中的異常?

+8

在catch塊中添加'e.printStackTrace()',你就會知道。 –

+3

請不要使用StringBuffer,因爲它在十多年前被StringBuilder所取代。 –

+0

如果你想知道它爲什麼會產生錯誤,也許你不應該拋棄你的異常,就好像它們沒有發生一樣。 –

回答

1

是的,如果你不打算處理或重新拋出異常,你不應該抓住它們。

相關問題