Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 14 of 14

Thread: Exception handling woes

  1. #1
    Member
    Join Date
    Sep 2013
    Posts
    64
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default Exception handling woes

    Ok, so I'm trying to work with files, and with files come exception handling, and with exception handling comes compilation errors!

    I have part of a function here that is used to retrieve information about a player. This information is in a file. I passed the name of the file that this information is in, it's under the variable "file".

    This code is supposed to catch an error if the passed argument "file" doesn't actually exist.

    Except this won't compile!!!! Why not?

                    Scanner inputFile;
     
                    String name = input.next();
     
                    // exception handling
                    try
                    {
                            inputFile = new Scanner(file);
     
                    } catch (FileNotFoundException ex)
                    {
                            System.err.println("FileNotFoundException: " + ex.getMessage());
                    }
     
                     // find player in file
                    while(inputFile.hasNext() && !nameFound)
                    {
                            fileName = inputFile.next();
     
                            System.out.println("fileName = " + fileName);
     
                            if (fileName.equals(name))
                                    nameFound = true;
                    }
     
                    inputFile.close();


    Here's the error:

    HTML Code:
    TicTacToe.java:152: error: variable inputFile might not have been initialized
                    while(inputFile.hasNext() && !nameFound)


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Exception handling woes

    Simply initialize it when you declare it.

    Scanner inputFile = null;

    You can learn more about why this is important and why it's necessary by reviewing the tutorial on Java variables.

  3. The Following User Says Thank You to GregBrannon For This Useful Post:

    ineedahero (September 23rd, 2013)

  4. #3
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Exception handling woes

    The problem occurs when you encounter a FileNotFoundException. In that case, your inputFile variable will not be initialized. So what should happen when you go to use it?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. The Following User Says Thank You to KevinWorkman For This Useful Post:

    ineedahero (September 23rd, 2013)

  6. #4
    Member
    Join Date
    Sep 2013
    Posts
    64
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default Re: Exception handling woes

    Ok guys, thanks for the help.

    I fixed the errors, but now I'm getting more exception handling problems!

    public Player createNewPlayer(java.io.File file)// throws Exception
            {
                    Player player = new Player();
                    java.io.FileWriter output = null;
     
                    try
                    {
                            output = new java.io.FileWriter(file, true);
     
                    } catch (FileNotFoundException ex)
                    {
                            System.err.println("FileNotFoundExcpetion: " + ex.getMessage());
     
                    } catch (IOException ex)
                    {
                            System.err.println("Caught IOException: " + ex.getMessage());
                    }
     
                    // receive player info
                    player.receiveName();
                    player.receiveSymbol();
     
     
                    // write player information to file
                    output.write(player.name + " " + player.symbol + " " + player.numWins + " " + player.numLosses + "\n");
     
                    output.close();
     
                    return player;
            }


    Here's the error:
    HTML Code:
    TicTacToe.java:209: error: unreported exception IOException; must be caught or declared to be thrown
                    output.write(player.name + " " + player.symbol + " " + player.numWins + " " + player.numLosses + "\n");
                                ^
    TicTacToe.java:211: error: unreported exception IOException; must be caught or declared to be thrown
                    output.close();
    I'm confused because this time it's all initialized; my previous code works perfectly. This one should be the same exact thing....but it isn't. I don't see why anything is wrong with those lines. I already reported the exception IOException up at the top....

  7. #5
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Exception handling woes

    You're only checking a single line in your try block above. What happens if you encounter the Exception on one of the lines not inside the try block?
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  8. #6
    Member
    Join Date
    Sep 2013
    Posts
    64
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default Re: Exception handling woes

    So every single time I output something to a file I have to check for exception handling? Isn't that a little redundant?

    And can I presume that the same holds for reading from a file?

  9. #7
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Exception handling woes

    Redundant? Error checking must be as frequent as the possibility of the error occurring. Typically, reading and writing to a file is done in loops, and the entire loop can be enclosed in a try/catch block, so REALLY, only one try/catch block should be required for each of the reading and writing loops. Both reading and writing could be contained in the same try/catch block with multiple "catches," but that may not be a good design.

  10. The Following User Says Thank You to GregBrannon For This Useful Post:

    ineedahero (September 23rd, 2013)

  11. #8
    Member
    Join Date
    Sep 2013
    Posts
    64
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default Re: Exception handling woes

    Ah, so it looks a little more like this:

    Player player = new Player();
                    java.io.FileWriter output = null;
     
                    // receive player info
                    player.receiveName();
                    player.receiveSymbol();
     
                    try
                    {
                            // assign FileWriter object to the specified file
                            output = new java.io.FileWriter(file, true);
     
                            // write info to the file
                            output.write(player.name + " " + player.symbol + " " + player.numWins + " " + player.numLosses + "\n");
     
                            // close the file
                            output.close();
     
                    } catch (FileNotFoundException ex)
                    {
                            System.err.println("FileNotFoundExcpetion: " + ex.getMessage());
     
                    } catch (IOException ex)
                    {
                            System.err.println("Caught IOException: " + ex.getMessage());
                    }
     
                    return player;


    Very nice. So I suppose every when you write to a file, even if it's like the ninth time in a row, it's always possible that a weird error comes out of nowhere.

    Thank you for your help.

  12. #9
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Exception handling woes

    I agree with what Greg said, but to show you why you need to error-check almost every method involving files:

    Java opens a file for reading or writing. Everything is okay. By your logic, we can be done error handling.
    But what if the user goes and deletes that file before the next line? Remember that users are nefarious and will do everything they can to break your program. What if the permissions on the file changes? What if the hard drive fills up when you're writing to the file? So much can go wrong, so you need to have error checking.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  13. The Following User Says Thank You to KevinWorkman For This Useful Post:

    ineedahero (September 23rd, 2013)

  14. #10
    Member
    Join Date
    Sep 2013
    Posts
    64
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default Re: Exception handling woes

    Eh, bit of a typo there. The word "every" shouldn't be in the second sentence.

    How come the edit button doesn't work? I click it and that loading circular icon thing comes up, and nothing ever happens.

  15. #11
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Exception handling woes

    Forum bug. Try opening it in a new tab.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  16. The Following User Says Thank You to KevinWorkman For This Useful Post:

    ineedahero (September 23rd, 2013)

  17. #12
    Member
    Join Date
    Sep 2013
    Posts
    64
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default Re: Exception handling woes

    While we're here, I figure I'll ask another question that's been on my mind about exception handling.

    My professor mentioned that we should use exception handling in two scenarios (given the program we're working on):
    1. Memory allocation
    2. Accessing a file

    I got the second one down, no problem.

    The first one is a little more confusing.
    By memory allocation, I'm assuming what's meant is every time you use the keyword "new".
    So, like:
    inputFile = new Scanner(file);
    And in that case, I just check to see if the file is found.

    But what about this line of code? Player is a class I created. Player player is just me creating a Player object named player.
    Player player = new Player();

    My question is this: in that line of code, I undoubtedly allocate memory....so is any exception handling necessary? And, if so, what exception do I throw?

    Thanks in advance.

  18. #13
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Exception handling woes

    Memory allocation? Every time a variable or object is declared, memory is allocated to store that item. That is done behind the scenes without programmer intervention. Would I expect anyone to put every variable declaration inside a try/catch block? Of course not. I'm not even sure what exception would be caught, but there's probably some obscure one I don't know about.

    Beyond that, there are no programmer specific tools in Java for reserving or allocating blocks of memory that i can think of, so I'm not sure what your professor is talking about. You should ask.

  19. #14
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Exception handling woes

    I again agree with what Greg said. But to add to that, exception handling doesn't really have anything *specifically* to do with either file handling or memory allocation (whatever that means).

    In Java, a method can declare the fact that it throws an Exception. There are two types of Exceptions: checked and unchecked. If a method has declared that it can throw a checked Exception (such as IOException), then the call to that method must be inside a try block (or you must delclare that method throws the Exception as well). Something like this:

    import java.io.IOException;
     
    public class Main {
     
    	public static void main(String... args){
    		try {
    			doSomethingDangerous();
    		} 
    		catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
     
    	static void doSomethingDangerous() throws IOException{
    		if(Math.random() < .5){
    			//this is not a good use of IOException but demonstrates the point
    			throw new IOException();
    		}
    	}
    }

    The classes you're using, such as Scanner, are really just Java code. In fact you can look at the code in the src.zip file that comes with your JDK. If you look at the source for Scanner, you'll see that some of its methods have declared that they can throw an IOException, so you have to put them in a try block.

    Similarly, you would only have to put a constructor in a try block if it declared that it threw a checked exception.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

Similar Threads

  1. Help with exception handling.
    By K0414 in forum Exceptions
    Replies: 3
    Last Post: April 19th, 2013, 02:18 PM
  2. need help in exception handling
    By gauravdudeja in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 8th, 2013, 06:14 AM
  3. [SOLVED] exception handling
    By Topflyt in forum Exceptions
    Replies: 5
    Last Post: December 22nd, 2011, 12:00 PM
  4. [SOLVED] Exception Handling
    By Melawe in forum What's Wrong With My Code?
    Replies: 2
    Last Post: December 21st, 2011, 07:39 PM
  5. Exception handling
    By AnithaBabu1 in forum Exceptions
    Replies: 6
    Last Post: August 27th, 2008, 09:37 AM