未报告的异常FileNotFoundException;必须被抓住或宣布被抛出

时间:2013-03-10 03:36:33

标签: java

我的代码导致以下错误 - 这是为什么?

2 errors found:
File: C:\Users\Name\P4.java  [line: 44]
Error: C:\Users\Name\P4.java:44: unreported exception FileNotFoundException; must be caught or declared to be thrown
File: C:\Users\Name\P4.java  [line: 46]
Error: C:\Users\Name\P4.java:46: exception java.io.FileNotFoundException is never thrown in body of corresponding try statement

这是导致错误的代码:

case Command.CMD_DO:
      NextCommand tmpReader;
      try {
       tmpReader = new NextCommand( c.getArg() );
      } 
      catch (FileNotFoundException e) {
       tmpReader = null;
       System.out.println( "Unable to open file:");
       System.out.println( "   " + e.getMessage());
      }

全班都在这里:

import java.io.FileNotFoundException;
import java.util.Stack;


public class P4 {

 public static void main( String[] args ) {

  // Start off assuming we're reading from the console and create a stack
  // for storing "pushed" readers
  NextCommand reader = new NextCommand();
  Stack<NextCommand> cmdStack = new Stack<NextCommand>();

  // The command we get and a flag to indicate whether it's time to exit
  Command c;
  boolean userRequestsExit = false;

  // For storing the history. We keep track of the depth of the stack, too.
  // Note that we could just use cmdStack.size() but that's a Vector operation rather
  // than a "pure" stack operation, so for the sake of pedagogy, we won't...
  History h = new History();
  int nestingLevel = 0;

  do {
   // Get a command
   c = reader.get();
   h.add( c, nestingLevel );

   switch (c.getCommand()) {

   // Do nothing in response to a comment
     case Command.CMD_COMMENT:
      break;

   // DO filename. See if we can start a reader up from the file.
   // If not, then print an error and continue from where we left off.
   // If so, push the current reader onto a stack and continue with the new one
     case Command.CMD_DO:
      NextCommand tmpReader;
      try {
       tmpReader = new NextCommand( c.getArg() );
      } 
      catch (FileNotFoundException e) {
       tmpReader = null;
       System.out.println( "Unable to open file:");
       System.out.println( "   " + e.getMessage());
      }
      // Success. Save current reader and switch to new one. We are
      // now nested one level deeper in DO files...
      if (tmpReader!=null) {
       cmdStack.push(reader);
       reader = tmpReader;
       nestingLevel++;
      }
      break;

   // DOC id "title" text 
     case Command.CMD_DOC:
    String[] docParts = c.getArg().split( "\"" );
    if (docParts.length != 3) {
     System.out.println( "ERROR: Invalid format: use DOC docid \"title\" text");
    }
    else {
     Document d = new Document( docParts[0].trim(),
              docParts[1].trim(),
              docParts[2].trim() );
     //Add document to database
     Database.documentList.add(d);
     if (d==null || d.getDocid()==null)
      System.out.println( "ERROR: Invalid DOC: " + d.getTitle() );
     else
      System.out.println( "Added document " + d.getDocid() );
    }
    break;

   // HISTORY
     case Command.CMD_HISTORY:
      System.out.println( h );
      break;

   // END. If the command-source stack is empty, we're done.
   // Otherwise, revert to the previous one and note that we are now
   // one level back up in the nesting of DO files.
     case Command.CMD_END:
    if (cmdStack.empty())
     userRequestsExit = true;
    else {
     reader = cmdStack.pop();
     nestingLevel--;
    }
    break;

   // Others
     default:
    System.out.println ("Only DOC, DO, HISTORY, and END commands work right now.");
   }
  } while (!userRequestsExit);

  // Courtesy exit message.
  System.out.println( "Thank you for playing." );
  System.out.println( "You processed " + h.numCommands()
       + " command"
       + (h.numCommands()==1 ? "" : "s")
       + " before you exited." );
 }

}

这是NextCommand类:

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

public class NextCommand implements NextCommandInterface  {

 private Scanner inStream;
 private boolean promptUser;
 private String nameOfFile;

 // Default constructor uses system input and requests prompting
 public NextCommand() {
  inStream = new Scanner( System.in );
  promptUser = true;
  nameOfFile = null;
 }

 // Alternate constructor to allow input from a file (no prompting)
 public NextCommand(String filename) throws FileNotFoundException {
  inStream = new Scanner( new File(filename));
  promptUser = false;
  nameOfFile = filename;
 }

 // Ask user for a command and process it to return a Command
 public Command get() {
  String inLine;

  // If we have no way to get input, pretend we hit the end
  if (inStream==null)
   return new Command( "END" );

  // Optionally prompt for the command
  if (promptUser)
   System.out.print( "Command? ");

  // Get a command (have to make sure EOF wasn't pressed)
  if (!inStream.hasNextLine())
   return new Command( "END" );

  inLine = inStream.nextLine();

  // Clean it up and return the results
  return new Command( inLine );

 }

 // A whimsical way to print this object out.
 public String toString() {
  if (nameOfFile == null)
   return "Commands being accepted from standard input";
  else
   return "Commands being accepted from " + nameOfFile;
 }
}

2 个答案:

答案 0 :(得分:1)

编译错误表明在FileNotFoundException中有P4个版本正在发挥作用。您已导入java.io.FileNotFoundException并尝试捕获。然后还有一些其他FileNotFoundException异常(根据编译器)被NextCommand构造函数抛出。

但这没有意义......

如果代码是您向我们展示的,并且编译错误就像您向我们展示的那样,那么我能想到的唯一解释是您需要重新编译某些内容

具体来说,您已经更改了NextCommand中的导入而没有重新编译它,然后是P4类。

我建议您删除然后重新编译所有“.class”文件。


唯一的另一种可能性是,您在与我们展示的两个类相同的包中定义了一个虚假版本的FileNotFoundException。如果你这样做,你的虚假课程将优先于真实课程。但是为了使“工作”作为解释,你还需要对Scanner执行相同的操作...因为真正的Scanner构造函数会抛出真正的FileNotFoundException ...这是检查的,因此必须在NextCommand构造函数签名中声明。在这一点上,我将把它视为“难以置信”。

答案 1 :(得分:1)

向您的FileNotFoundException方法调用添加main()投掷,喜欢这样:

public static void main(String[] args)  throws FileNotFoundException {

然后删除try-catch块。让我知道这是怎么回事。