当行超过 80 (java) 时抛出异常

Throw an exception when line is above 80 (java)

我正在尝试编写一个程序,它将 java 文件作为输入(在程序中指定)并逐行读取它。如果一行超过 80 个字符,它会抛出异常,如果抛出异常,程序会打印出太长的行,并继续处理程序的其余部分。

import java.io.*;
import java.util.*;

public class LinePolice
{
   public static void main(String[] args) throws LinePoliceTooLongException
   {
      try
      {
         File file = new File("NameOrientation.java");
         FileReader fileReader = new FileReader(file);
         BufferedReader bufferedReader = new BufferedReader(fileReader);
         StringBuffer stringBuffer = new StringBuffer();
         String line;
         while ((line = bufferedReader.readLine()) != null)
         {
            LinePoliceTooLongException x = new LinePoliceTooLongException(line); 
            if (line.length() > 80)
               throw x;
         }
         fileReader.close();
      }
      catch (IOException e)
      {

      }
   }
}


public class LinePoliceTooLongException extends Exception
{
   LinePoliceTooLongException(String message)
   {
      super(message);
   }
}

当我 运行 它与以下文件一起使用时,它会选择第一行超过 80 行,但不会继续处理文件。

import java.awt.*;
import javax.swing.*;

public class NameOrientation
{
   public static void main(String[] args)
   {
      JFrame frame = new JFrame("NameOrientation");

      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      JPanel primary = new JPanel();
      primary.setBackground(Color.green);
      primary.setPreferredSize(new Dimension(250, 250));

      JLabel label1 = new JLabel("********************************************************");
      JLabel label2 = new JLabel("**************************************************************");

      primary.add(label1);
      primary.add(label2);

      frame.getContentPane().add(primary);
      frame.pack();
      frame.setVisible(true);
   }
}   

如果可能的话,有人可以告诉我哪里出了问题,以及我可以做些什么来尝试让它发挥作用。感谢所有帮助

            while ((line = bufferedReader.readLine()) != null)
            {
                LinePoliceTooLongException x = new LinePoliceTooLongException(line); 
                try{
                    if (line.length() > 80)
                       throw x;
                }catch(LinePoliceTooLongException le){
                    System.out.println("Line:"+line);
                }
             }

由于您从 while 循环中抛出 LinePoliceTooLongException 而未捕获它,因此您无法继续执行其余的行。您必须在 while 循环本身中捕获异常。

在您的代码中,您正在创建异常

 LinePoliceTooLongException x = new LinePoliceTooLongException(line); 

扔了它,你没有接住它。这就是您的程序未正确完成的原因。我想你现在应该已经明白了。

要解决这个问题,您可以添加 catch 块来捕获您刚刚抛出的异常。如果你这样做,那将是非常可怕的,抛出异常并在抛出后立即捕获它没有任何意义。无论您想在 catch block 中做什么,都在 if 中进行,不要抛出任何异常。

 while ((line = bufferedReader.readLine()) != null)
     {
       if (line.length() > 80){
          System.out.println("Line is more than 80 characters and can not be processed: " + line);
     }
 }