【问题标题】:java try catch block does not print the information that I want it tojava try catch 块不打印我想要的信息
【发布时间】:2015-11-12 02:42:45
【问题描述】:

我希望用户在命令行上输入文件名。如果他们不输入任何内容,我应该打印信息,说明文件未处理并退出。这是我的 try catch 块

try{
      parser.openFile(args[0]);
      if(parser.getCounter() == 3)
        {
          System.out.println("File was processed: true");
        }
        else
        {
          System.out.println("File was processed: false. Missing information.");
        }
        //found = true;
      }
        catch (IOException e)
          {
             e.printStackTrace();
             System.out.println("File was processed: false. Re-enter filename.");
             //fName = keyboard.nextLine();
        }

openFile 方法在我的课堂上,它就在这里,以防万一有人需要它:

  public void openFile (String filename)throws IOException{
    fis = new FileInputStream(filename);
    br = new BufferedReader(new InputStreamReader(fis));
    String thisLine;
    thisLine = br.readLine();
    while(thisLine != null)
    {
        lines.add(thisLine);
        thisLine = br.readLine();
    }
}

不知何故“文件已处理:错误。重新输入文件名。”当命令行中没有文件名时不会打印出来。谁能帮帮我?

【问题讨论】:

  • 你在控制台看到了什么错误?
  • 尝试检查 args 的长度以确定用户是否输入了参数,而不是依赖 FileInputStream 来抛出异常。
  • 我可以使用 if-else 语句检查,但是教授希望我们使用 try-catch ......我应该如何将它融入 try-catch 块?
  • 尝试使用 catch (Exception e) 代替 IOException 并检查结果。

标签: java exception try-catch


【解决方案1】:

您可能会遇到不同的异常。也许

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:

尝试验证args的内容

例子:

public class TesteArgs {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Inform a valid name...");
            System.exit(0);
        }
        // continue handling your args param
        System.out.println(args[0]);
    }
}

【讨论】:

  • 是的,这是我得到的例外。我可以使用 if-else 语句来检查,但是教授希望我们使用 try catch,我不知道如何将它混合到 try catch 块中......
【解决方案2】:

在你的 catch 语句中将你的 IOException 更改为 Exception,这样可以很好地为你捕获异常。

【讨论】:

    【解决方案3】:

    您可以在try{}catch{} 块中捕获多个异常。

    您必须先捕获特定异常(ArrayIndexOutOfBoundsException,它是 Exception 的子级),然后再捕获通用异常 (Exception)。

    示例代码:

        try{
            // Your code
            File f = new File ("a.txt");
            FileInputStream fio = new FileInputStream(f);
        }catch(ArrayIndexOutOfBoundsException ae ){
            System.out.println(ae);
        }catch(IndexOutOfBoundsException ee ){
            System.out.println(ee); 
        }catch(IOException ioe ){
            System.out.println(ioe);    
        }catch(RuntimeException re ){
            System.out.println(re);
        }catch(Exception e ){
            System.out.println(e);      
        }catch(Throwable t ){
            System.out.println(t);      
        }
    

    看看exceptions的层次结构

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 2011-05-04
      • 1970-01-01
      • 2011-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多