0

Here is my code. The FileNotFoundException is not being thrown for some reason when i give it a fileName that does not exist.

 public static String Question1( String fileName )
 {   
    String message = ""; 
    if ( fileName == null )
    {   
        fileName = "files/question1/sample.txt"; 
    }

    try
    {  

        Scanner fileScan = new Scanner( new File ( fileName ));

        while ( fileScan.hasNext() )
        {
            String readLine = fileScan.nextLine();

            if ( message.equals( "" ) )
            {
                message = readLine + "\n";
            }
            else
            {
                message = message + readLine + "\n";
            }
        }
    }

    catch ( FileNotFoundException e )
    {
        message = "Error: Could not find file!";
    }

    return message;
 }

When i run the code with a fileName that does not exist, the message returned is "" instead of "Error: Could not find file!"

leppie
  • 115,091
  • 17
  • 196
  • 297

2 Answers2

0

I call shenanigans :-) I suspect the file does exist in your case since this code works just fine:

import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;

public class Test {
    public static String Question1(String fileName) {   
        String message = "";
        if ( fileName == null )
            fileName = "files/question1/sample.txt"; 

        try {  
            Scanner fileScan = new Scanner(new File(fileName));
            while (fileScan.hasNext()) {
                String readLine = fileScan.nextLine();
                if (message.equals("")) {
                    message = readLine + "\n";
                } else {
                    message = message + readLine + "\n";
                }
            }
        } catch (FileNotFoundException e) {
            message = "Error: Could not find file!";
        }

        return message;
    }

    public static void main(String[] args) {
        System.out.println(Question1("no_such_file.txt"));
    }
}

Running that outputs, as expected:

Error: Could not find file!

When I create that file, the program outputs its contents.

I suggest going back to look at your file system again, then run your code through a single-stepping debugger to track the code flow.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

Are you sure the exception FileNotFoundException is thrown?

What could be happening is at the relative path of where this class is placed ,the file that you think is not present,could be present.

abhati
  • 309
  • 1
  • 6