1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Redefining Exception Java

  1. Mar 24, 2015 #1
    1. The problem statement, all variables and given/known data

    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.

    2. Relevant equations

    None

    3. The attempt at a solution

    My code is the following:

    Code (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:

    Code (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.
     
  2. jcsd
  3. Mar 25, 2015 #2

    Mark44

    Staff: Mentor

    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.
     
  4. Mar 25, 2015 #3

    Borg

    User Avatar
    Science Advisor
    Gold Member

    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.
     
  5. Mar 25, 2015 #4
    Hm, I should definitely go re-read the exception chapter in my book. I thought I understood it but I didn't.
     
  6. Mar 25, 2015 #5
    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:

    Code (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: Mar 25, 2015
  7. Mar 26, 2015 #6

    Mark44

    Staff: Mentor

    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.
     
  8. Mar 26, 2015 #7
    I actually figured it out. It was because my inputStream was still null in my finally block.
     
  9. Mar 26, 2015 #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?
     
  10. Mar 26, 2015 #9

    Borg

    User Avatar
    Science Advisor
    Gold Member

    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.
     
  11. Mar 26, 2015 #10
    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?
     
  12. Mar 26, 2015 #11

    Borg

    User Avatar
    Science Advisor
    Gold Member

    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.
     
  13. Mar 26, 2015 #12
    Oh, I see. Ty!
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: Redefining Exception Java
  1. Java prob. (Replies: 1)

  2. HeapSort Java (Replies: 3)

Loading...