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

  • Comp Sci
  • Thread starter Robben
  • Start date
  • Tags
    Java
In summary: UnknownFileException(String message) { super(message); }...is not the same as this:public UnknownFileException(String message) { super(message, true); }The first would throw a compile error due to an unreported FileNotFoundException, while the second would not. In summary, UnknownFileException does not exist.
  • #1
Robben
166
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
  • #2
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 Robben
  • #3
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.
 
  • #4
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.
 
  • #5
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:
  • #6
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 Robben
  • #7
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.
 
  • #8
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?
 
  • #9
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!
 

What is "Redefining Exception Java"?

"Redefining Exception Java" is a concept in the Java programming language that refers to the ability to modify or customize existing exception classes or create new ones to better suit the needs of a specific program or project.

Why is "Redefining Exception Java" important?

"Redefining Exception Java" allows developers to handle errors and exceptions in a more efficient and effective way by tailoring them to fit the specific needs of their program. This can result in more accurate error reporting and better handling of unexpected situations.

How does "Redefining Exception Java" differ from traditional exception handling?

In traditional exception handling, developers are limited to using predefined exception classes provided by the Java language. With "Redefining Exception Java", developers have the flexibility to create their own custom exception classes that are better suited for their specific project.

What are some potential drawbacks of "Redefining Exception Java"?

One potential drawback is that creating custom exception classes can add complexity to the code and may require additional maintenance. Additionally, using non-standard exceptions may make it more difficult for other developers to understand and debug the code.

How can I start using "Redefining Exception Java" in my projects?

To start using "Redefining Exception Java", you can begin by familiarizing yourself with the concept and understanding how it differs from traditional exception handling. Then, you can experiment with creating custom exception classes and incorporating them into your code as needed.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
10
Views
10K
  • Engineering and Comp Sci Homework Help
Replies
5
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
8
Views
9K
  • Engineering and Comp Sci Homework Help
Replies
6
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
16
Views
4K
  • Programming and Computer Science
Replies
28
Views
3K
  • Programming and Computer Science
Replies
4
Views
3K
  • Programming and Computer Science
Replies
4
Views
2K
  • Programming and Computer Science
Replies
3
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
5
Views
4K
Back
Top