简体   繁体   English

即使存在throws语句,也接收FileNotFoundException

[英]receiving FileNotFoundException even though throws statement is present

I have written the following code that prints a list of randomly generated characters to a file, then reads them from a file, encrypts them using an exclusive or, and then prints them again. 我编写了以下代码,该代码将随机生成的字符列表打印到文件中,然后从文件中读取它们,然后使用异或将其加密,然后再次打印。 The issue is that I am receiving a FileNotFoundException even though I have placed it in a throws statement. 问题是,即使我将它放在throws语句中,我仍然收到FileNotFoundException。

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws FileNotFoundException {


    //get integer mask from user input
    int mask = getMask();
    System.out.println("TEMP mask Value is: " + mask);

    //create 50 character random String and save to file
    String randomString = getRandomString(50);
    System.out.println("Original Random Character String: " + '\n' + randomString);

    //save 50 Char String from file
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Saving encrypted string...");
    System.out.print("Enter a file name: ");
    String fileName = keyboard.next();
    File outputFile = new File(fileName);
    saveFile(fileName, randomString);
    /*System.out.println("Saving Original Random Character string...");
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter a file name: ");
    String fileName = keyboard.next();
    File outputFile = new File(fileName);
    PrintWriter fileWriter = new PrintWriter(outputFile);
    fileWriter.println(randomString);

    fileWriter.close();//CLOSE OF FILEWRITER
    */


    //scan in from file
    Scanner file = new Scanner(outputFile);
    String inputString = file.nextLine();
    //print what was just scanned in from file
    System.out.print("Original random character string from the file" + 
            '\n' + inputString + '\n');

    //apply mask by convertig String to char using loop
    String maskedString = maskString(inputString, mask);
    System.out.print("Encrypted character string: " + '\n' + maskedString + '\n');
    /*String maskedString = "";
    for(int i = 0; i < inputString.length(); i++){
    char charMasked = (char)(((int) inputString.charAt(i))^mask);
    maskedString += charMasked;
    }//end of for loop
    System.out.print("Encrypted character string: " + '\n' + maskedString + '\n');
    */

    //save encrypted string
    System.out.println("Saving encrypted string...");
    System.out.print("Enter a file name: ");
    String encryptedFileName = keyboard.nextLine();
    saveFile(encryptedFileName, maskedString);





}//end of main method
/**
 * Preconditions: must call randomString method to get random 
 * characters
 * Postconditions: user will have a string of random characters of desired
 * length
 * @param count allows user to choose how many random characters to return
 */
public static String getRandomString(int count)throws FileNotFoundException{

    String listChars = "";
    for (int i = 0; i < count; i++) {
        char randomChar = (char) ((Math.random() * 255) + 32);/////////////////////getting less than 50 characters sometimes, possible control characters?
        listChars += randomChar;
    }//end of for loop
    return listChars;
}//end of randomString method

/**
 * Precondition: must call getMask method to get prompt user to enter the 
 * encryption mask that will be used to encrypt the file input
 * Postcondition: user has entered an integer string that will be used to 
 * encrypt the 50 char random String we will read from a file
 * @return output, which is the user entered integer value
 */

public static int getMask(){
    //Prompt user to enter integer mask
    System.out.print("Enter the encryption mask: ");
    Scanner keyboard = new Scanner(System.in);
    int output = keyboard.nextInt();
    return output;
}//end of getMask method

public static void saveFile(String fileName, String toBePrinted)throws FileNotFoundException{

    File outputFile = new File(fileName);
    PrintWriter fileWriter = new PrintWriter(outputFile);
    fileWriter.println(toBePrinted);

    fileWriter.close();//CLOSE OF FILEWRITER
}//end of saveFile method

public static String maskString(String inputString, int mask){
String maskedString = "";
    for(int i = 0; i < inputString.length(); i++){
    char charMasked = (char)(((int) inputString.charAt(i))^mask);
    maskedString += charMasked;
    }//end of for loop
    return maskedString;
}//end of maskString method

Upon execution of my code I receive something along the lines of Exception in thread "main" java.io.FileNotFoundException: (No such file or directory) . 在执行我的代码后,我Exception in thread "main" java.io.FileNotFoundException: (No such file or directory)收到了类似Exception in thread "main" java.io.FileNotFoundException: (No such file or directory) I thought this error would be prevented by my use of the throws FileNotFoundException statement. 我认为可以通过使用throws FileNotFoundException语句来防止此错误。

I have reviewed the Oracle Java Tutorial here 我已经在这里查看了Oracle Java教程

I am honestly trying but it is just not clicking with me. 我正在诚实地尝试,但只是没有点击我。 I have only ever used a try-catch statement to catch exceptions like this. 我只用过try-catch语句来捕获这样的异常。 Is that what I need to do here every single time I try and save a file which is not previously created? 这是我每次尝试保存以前未创建的文件时需要在这里执行的吗?

throws clause in the method signature only means that "I am aware that this method can throw this exception and I do NOT catch it here, so the caller should catch it." 方法签名中的throws子句仅表示“我知道此方法会引发此异常,并且在此处未捕获此异常,因此调用方应捕获该异常。”

In your example you are just tricking your compiler so that it won't complain about uncaught exception. 在您的示例中,您只是在欺骗编译器,以便它不会抱怨未捕获的异常。

By adding the FileNotFoundException you are stating the function may throw this exception, but you are not adding anything that will catch and suppress the Exception. 通过添加FileNotFoundException,您正在声明该函数可能会引发此异常,但是您并未添加任何将捕获并抑制该异常的内容。

I would wrap your code into a function/class, then in your main code block add a try block that calls your function/class, and add a catch block for the FileNotFoundException. 我会将您的代码包装到一个函数/类中,然后在您的主代码块中添加一个try块来调用您的函数/类,并为FileNotFoundException添加catch块。

The throws clause doesn't avoid the exception from being thrown. throws子句不能避免引发异常。 Actually, it just declares the method as throwing such exception so that other methods calling it can treat it accordingly. 实际上,它只是将方法声明为抛出此类异常,以便其他调用它的方法可以相应地对其进行处理。

If you want to suppress exceptions, you must surround your statement with a try-catch statement. 如果要抑制异常,则必须在语句周围加上try-catch语句。 However, suppressing exceptions is not a good practice. 但是,禁止例外不是一个好习惯。 You should instead treat them correctly and show a compatible message to your user. 您应该正确对待它们,并向您的用户显示兼容消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM