1

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

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;
 }
}
4

2 回答 2

3

将 throws 添加FileNotFoundException到您的main()方法调用中,如下所示:

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

然后删除 try-catch 块。让我知道情况如何。

于 2013-04-27T13:59:10.833 回答
1

编译错误是说FileNotFoundExceptionP4. 有java.io.FileNotFoundException一个你已经导入并试图捕捉的东西。然后是构造函数抛出了一些其他FileNotFoundException异常(根据编译器)NextCommand

但这没有意义...

如果代码是你给我们看的,编译错误是你给我们看的,那么我能想到的唯一解释就是你需要重新编译一些东西

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

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


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

于 2013-03-10T04:43:57.003 回答