How can I redefine the FileNotFoundException in Java for my class practice?

  • Context: Comp Sci 
  • Thread starter Thread starter Robben
  • Start date Start date
  • Tags Tags
    Java
Click For Summary

Discussion Overview

The discussion revolves around redefining the FileNotFoundException in Java by creating a custom exception class, UnknownFileException, for a class practice. Participants explore the challenges of handling file input and output exceptions, particularly when a file is not found.

Discussion Character

  • Homework-related
  • Technical explanation
  • Debate/contested

Main Points Raised

  • One participant shares their attempt to create a custom exception class, UnknownFileException, that extends FileNotFoundException, and describes the context in which it should be thrown.
  • Another participant points out that the original FileReader and FileOutputStream classes only throw FileNotFoundException, and thus the custom exception will not be thrown automatically.
  • There is a suggestion that the participant should catch the FileNotFoundException and then throw the UnknownFileException, but this leads to further compile errors due to unhandled exceptions.
  • Concerns are raised about the placement of inputStream and outputStream close calls, suggesting they should be in a finally block to ensure they execute regardless of errors.
  • A participant expresses uncertainty about their understanding of exception handling and acknowledges the need to revisit the relevant material.

Areas of Agreement / Disagreement

Participants generally agree on the limitations of extending the FileNotFoundException and the need to handle the original exception. However, there is no consensus on the best approach to implement the desired functionality without encountering compile errors.

Contextual Notes

Participants note that the custom exception needs to be handled properly to avoid compile errors, and there are unresolved issues regarding the correct implementation of exception handling in the provided code.

Robben
Messages
166
Reaction score
2

Homework Statement



I want to redefine the FileNotFoundException by creating a new class which extends it, but I am having difficulty. For my class practice, if no file is selected or passed in, an UnknownFileException should occur.

Homework Equations



None

The Attempt at a Solution



My code is the following:

Java:
import java.io.FileNotFoundException;

public class UnknownFileException extends FileNotFoundException {

    public UnknownFileException() {
        super("We couldn't tell what file this is");     
    }

    public UnknownFileException(String message) {
        super(message);   
    }  
}

Now, my other code which throws this exception:

Java:
public class practice {
    public String[] array;   
    public String line;
    public PrintWriter outputStream = null;   
    public Scanner inputStream = null;  
   
    public practice(String fileName) {
        array = new String[100];
        
        try {                   
            inputStream = new Scanner(new FileReader(fileName));
            line = inputStream.nextLine();
            array[0] = line;

            for (int i = 1; i < array.length; i++) {
                array[i] = inputStream.nextLine();   
            }

           inputStream.close();
           outputStream = new PrintWriter(new FileOutputStream("newFile.txt"));
           //outputStream.close();?       
       
       } catch(UnknownFileException e) {
           System.out.println(e.getMessage());
       }   
    }

But I get a compile error stating an unreported FileNotFoundException.
 
Physics news on Phys.org
Robben said:

Homework Statement



I want to redefine the FileNotFoundException by creating a new class which extends it, but I am having difficulty. For my class practice, if no file is selected or passed in, an UnknownFileException should occur.

Homework Equations



None

The Attempt at a Solution



My code is the following:

Java:
import java.io.FileNotFoundException;

public class UnknownFileException extends FileNotFoundException {

    public UnknownFileException() {
        super("We couldn't tell what file this is");    
    }

    public UnknownFileException(String message) {
        super(message);  
    } 
}

Now, my other code which throws this exception:

Java:
public class practice {
    public String[] array;  
    public String line;
    public PrintWriter outputStream = null;  
    public Scanner inputStream = null; 
  
    public practice(String fileName) {
        array = new String[100];
       
        try {                  
            inputStream = new Scanner(new FileReader(fileName));
            line = inputStream.nextLine();
            array[0] = line;

            for (int i = 1; i < array.length; i++) {
                array[i] = inputStream.nextLine();  
            }

           inputStream.close();
           outputStream = new PrintWriter(new FileOutputStream("newFile.txt"));
           //outputStream.close();?      
      
       } catch(UnknownFileException e) {
           System.out.println(e.getMessage());
       }  
    }

But I get a compile error stating an unreported FileNotFoundException.
It wouldn't be a compile error, since this would be happening at run-time, or at least when the Java Virtual Machine is running.

Here's what I think is happening. When you run your code, the practice() constructor gets called with a bogus name -- the name of a file that doesn't exist. The FileReader constructor throws a FileNotFoundException, not the UnknownFileException that you think will be thrown. You have a catch clause to handle UnknownFileException, but you don't have a catch for FileNotFoundException, so the system is reporting an unhandled exception.

Your custom exception needs to do something different from the exception class it inherits from -- that's what you need to focus on. Then set things up so that you can handle this different behavior.
 
  • Like
Likes   Reactions: Robben
Mark44 said:
It wouldn't be a compile error, since this would be happening at run-time, or at least when the Java Virtual Machine is running.
FileNotFoundException doesn't extend RuntimeException so it is a compile error.

@Robben, both the FileReader and FileOutputStream classes only throw FileNotFoundException. Just because you wrote a class that extends FileNotFoundException, doesn't mean that FileReader and FileOutputStream will suddenly change to throw your new, extended class.

The general purpose of extending an Exception class is to provide additional information to later code. The only thing that you could do with your code is to catch the FileNotFoundException and throw a new type of Exception after catching the original FileNotFoundException . However, when you do that, you will then get a compile error saying that the new type of Exception isn't handled either. Do you know why? Have you studied methods that throw Exceptions?

BTW, your inputStream.close() and outputStream.close() calls should go in a finally{} block. Otherwise, if there is an error, they won't get called and could stay open.
 
Borg said:
FileNotFoundException doesn't extend RuntimeException so it is a compile error.

@Robben, both the FileReader and FileOutputStream classes only throw FileNotFoundException. Just because you wrote a class that extends FileNotFoundException, doesn't mean that FileReader and FileOutputStream will suddenly change to throw your new, extended class.

The general purpose of extending an Exception class is to provide additional information to later code. The only thing that you could do with your code is to catch the FileNotFoundException and throw a new type of Exception after catching the original FileNotFoundException . However, when you do that, you will then get a compile error saying that the new type of Exception isn't handled either. Do you know why? Have you studied methods that throw Exceptions?

BTW, your inputStream.close() and outputStream.close() calls should go in a finally{} block. Otherwise, if there is an error, they won't get called and could stay open.

Hm, I should definitely go re-read the exception chapter in my book. I thought I understood it but I didn't.
 
Borg said:
@Robben, both the FileReader and FileOutputStream classes only throw FileNotFoundException. Just because you wrote a class that extends FileNotFoundException, doesn't mean that FileReader and FileOutputStream will suddenly change to throw your new, extended class.

The general purpose of extending an Exception class is to provide additional information to later code. The only thing that you could do with your code is to catch the FileNotFoundException and throw a new type of Exception after catching the original FileNotFoundException . However, when you do that, you will then get a compile error saying that the new type of Exception isn't handled either. Do you know why? Have you studied methods that throw Exceptions?

BTW, your inputStream.close() and outputStream.close() calls should go in a finally{} block. Otherwise, if there is an error, they won't get called and could stay open.

I have edited my code using the suggestions you guys mentioned (well hopefully I did) but, it doesn't do what I want it to do.

My code is the following:

Java:
public class practice {
    public String[] array;
    public String line;
    public PrintWriter outputStream = null;
    public Scanner inputStream = null;

    public practice(String fileName)  throws UnknownFileException {
    array = new String[100];

    try {
        inputStream = new Scanner(new FileReader(fileName));
        line = inputStream.nextLine();
        array[0] = line;

        for (int i = 1; i < array.length; i++) {
            array[i] = inputStream.nextLine();
        }

        outputStream = new PrintWriter(new FileOutputStream("newFile.txt"));

    } catch(UnknownFileException e) {
        System.out.println(e.getMessage());
    } catch (FileNotFoundException e) {
        throw new UnknownFileException(e.getMessage());
    } finally {
        inputStream.close();  
    }
}

But now when I go and run my driver and put in an invalid filename I get a nullpointerexception instead? Instead of catching printing out the e.getMessage() I caught, it is now giving me a nullpointerexception. I am really confused in what's wrong with my code.
 
Last edited by a moderator:
Robben said:
I have edited my code using the suggestions you guys mentioned (well hopefully I did) but, it doesn't do what I want it to do.

My code is the following:

Java:
public class practice {
    public String[] array;
    public String line;
    public PrintWriter outputStream = null;
    public Scanner inputStream = null;

    public practice(String fileName)  throws UnknownFileException {
    array = new String[100];

    try {
        inputStream = new Scanner(new FileReader(fileName));
        line = inputStream.nextLine();
        array[0] = line;

        for (int i = 1; i < array.length; i++) {
            array[i] = inputStream.nextLine();
        }

        outputStream = new PrintWriter(new FileOutputStream("newFile.txt"));

    } catch(UnknownFileException e) {
        System.out.println(e.getMessage());
    } catch (FileNotFoundException e) {
        throw new UnknownFileException(e.getMessage());
    } finally {
        inputStream.close();
    }
}

But now when I go and run my driver and put in an invalid filename I get a nullpointerexception instead? Instead of catching printing out the e.getMessage() I caught, it is now giving me a nullpointerexception. I am really confused in what's wrong with my code.

One thing that jumps out at me is that your try block is too big. You should bracket only the questionable code with try and catch, not the eight or so lines you have. In the first line of your try block, the FileReader ctor will throw a FileNotFoundException "if the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading" -- per the Oracle docs for the FileReader class.

Right about now would be an excellent time to use a debugger of some kind, so that you can narrow down exactly where any exception is being thrown. Seeing all of your code would also be helpful.
 
  • Like
Likes   Reactions: Robben
Mark44 said:
One thing that jumps out at me is that your try block is too big. You should bracket only the questionable code with try and catch, not the eight or so lines you have. In the first line of your try block, the FileReader ctor will throw a FileNotFoundException "if the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading" -- per the Oracle docs for the FileReader class.

Right about now would be an excellent time to use a debugger of some kind, so that you can narrow down exactly where any exception is being thrown. Seeing all of your code would also be helpful.

I actually figured it out. It was because my inputStream was still null in my finally block.
 
Actually, I do have a question regarding your post. You said I should bracket only the questionable code, but where do I put the unquestionable code? I can't place it outside nor inside the finally block because the inputStream is already closed so I am confused on where to put them?
 
Robben said:
Actually, I do have a question regarding your post. You said I should bracket only the questionable code, but where do I put the unquestionable code? I can't place it outside nor inside the finally block because the inputStream is already closed so I am confused on where to put them?
Your outputStream can also throw an exception. I would move that below the finally block into its own try/catch/finally block.

Good job on having your constructor throwing your UnknownFileException class. However, the catch block where you catch the UnknownFileException will never happen - again, the Scanner and PrintWriter classes don't throw it. Only your practice constructor throws that exception so only a method that calls the practice constructor could ever successfully catch it.
 
  • #10
Borg said:
Your outputStream can also throw an exception. I would move that below the finally block into its own try/catch/finally block.

Good job on having your constructor throwing your UnknownFileException class. However, the catch block where you catch the UnknownFileException will never happen - again, the Scanner and PrintWriter classes don't throw it. Only your practice constructor throws that exception so only a method that calls the practice constructor could ever successfully catch it.

I see, so I should delete my catch block for the unknownfileexception if I don't have a method that class the practice constructor? And if I do have a method that calls the practice constructor then I would leave it alone as is?
 
  • #11
Robben said:
I see, so I should delete my catch block for the unknownfileexception if I don't have a method that class the practice constructor? And if I do have a method that calls the practice constructor then I would leave it alone as is?
I don't understand this completely - too many vague pronoun references and incomplete phrasing.

Yes, delete the UnknownFileException catch block. If you want to catch it somewhere, create a main() method and call new practice(); in that. It will force you to catch the exception that practice throws.
 
  • #12
Borg said:
I don't understand this completely - too many vague pronoun references and incomplete phrasing.

Yes, delete the UnknownFileException catch block. If you want to catch it somewhere, create a main() method and call new practice(); in that. It will force you to catch the exception that practice throws.

Oh, I see. Ty!
 

Similar threads

  • · Replies 10 ·
Replies
10
Views
11K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 8 ·
Replies
8
Views
10K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 2 ·
Replies
2
Views
7K
  • · Replies 16 ·
Replies
16
Views
5K
  • · Replies 4 ·
Replies
4
Views
3K