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

1

コンパイルエラーは、で2つのバージョンが使用FileNotFoundExceptionされていることを示していP4ます。java.io.FileNotFoundExceptionあなたが輸入して捕まえようとしているものがあります。次に、(コンパイラーによると)コンストラクターによってスローされているという他のFileNotFoundException例外があります。NextCommand

しかし、それは意味がありません...

コードがあなたが私たちに示した通りであり、コンパイルエラーがあなたが私たちに示した通りである場合、私が考えることができる唯一の説明はあなたが何かを再コンパイルする必要があるということです。

具体的には、インポートNextCommandを再コンパイルせずに、次にP4クラスを変更しました。

すべての「.class」ファイルを削除してから再コンパイルすることをお勧めします。


FileNotFoundException他の唯一の可能性は、あなたが私たちに示した2つのクラスと同じパッケージでの偽のバージョンを定義したことです。そうすると、偽のクラスが実際のクラスよりも優先されます。Scannerしかし、その「機能」を説明として使用するには、 ...で同じことを行う必要があります。これは、実際のScannerコンストラクターが実際の...をスローするため、チェックされ、コンストラクターの署名FileNotFoundExceptionで宣言する必要があるためです。NextCommandこの時点で、これを「不可解」として却下します。

于 2013-03-10T04:43:57.003 に答える