Results 1 to 4 of 4
  1. #1
    fredlo2010 is offline Member
    Join Date
    Jan 2014
    Posts
    17
    Rep Power
    0

    Default Best Try/Catch/Finally

    Hello guys,

    I was wondering whats the best way to implement an error catching sequence.

    I was developing a program to write to a . csv file. and this is one of the methods in it and how I thought Try/ Catch should be implemented. Then after reading my book I am a little confused. So I have three different possibilities and I would like the experts out there to help find out whats the best developers approach.

    Another auxiliary class with some constants:

    Java Code:
    public class Constants
    {
        
        /**
         * Constant name of the file.
         */
        public static final String fileName= "inventory.csv";
    
        /**
         * Constant headers of the file.
         */
        public static final String headers= "Description,Quantity,Price,UPC"+ "\n";
    
        /**
         * Constant initial values of the file.
         */
        public static final String originalBody="Sony Headphones,15,3.99,123456" + "\n"+
                                                "Motorola Tablet,55,499,987654" + "\n"+
                                                "HDMI Cables,101,16.99,789456";
        
        /**
         * Constant Main Menu items.
         */
        public static final String upperMenu= "1. Cycle through inventory." + "\n" +
                                              "2. Display total value of inventory"  + "\n" +
                                              "3. Add product."  + "\n" +
                                              "4. Search product (by UPC)" + "\n" +
                                              "5. Reset original file."  + "\n" +
                                              "6. Exit."+ "\n";
        
        // Error handling constants.
    
        /**
         * Constant for error we file cannot be accessed.
         */
            public static final String fileNotAccess = "File could not be accessed!" + "\n";
    
        /**
         * Constant for error when file cannot be found.
         */
        public static final String fileNotFound = "File was not found!" + "\n";
    }


    The way I did it:

    Java Code:
        /**
         * Reset the file 'inventory.csv' to its original state.
         * @throws IOException
         */
        public void resetFile() throws IOException
        {
            try
            {
                FileWriter fw = new FileWriter(Constants.fileName);
                
                fw.append(Constants.headers);
                fw.append(Constants.originalBody);
                
                fw.flush();
                fw.close();       
                
                System.out.println("File Successfully restored."+ "\n");
                
            }catch (IOException ex){
                System.out.println(Constants.fileNotAccess);
            }
        }
    The way I saw it and how my book describes it:
    Java Code:
        public void resetFile() throws IOException
        {
            
            FileWriter fw = new FileWriter(Constants.fileName);
            
            try
            {
                fw.append(Constants.headers);
                fw.append(Constants.originalBody);
                
                System.out.println("File Successfully restored."+ "\n");          
            }catch (IOException ex){
                System.out.println(Constants.fileNotAccess);
            }finally{
                fw.flush();
                fw.close();  
            }
        }

    The way the books says its the best:

    Java Code:
        public void resetFile() throws IOException
        {        
            
            try
            {
                FileWriter fw = new FileWriter(Constants.fileName);
            
                try
                {
                    fw.append(Constants.headers);
                    fw.append(Constants.originalBody);
    
                    System.out.println("File Successfully restored."+ "\n");                        
                }finally{
                    fw.flush();
                    fw.close();
                }
            }catch (IOException ex){
                System.out.println(Constants.fileNotAccess); 
            }
        }
    Thanks a lot for the help :)

  2. #2
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,105
    Rep Power
    6

    Default Re: Best Try/Catch/Finally

    Well your code is very conflicting in nature. All your methods declare that they throw an IOException, yet in stead of doing that, they catch them in stead.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  3. #3
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    990
    Rep Power
    2

    Default Re: Best Try/Catch/Finally

    The problem with your construction is that the methods to clean up (flush() and close()) are never fired when something goes booboo. If the constructor of FileWriter or the append method throw an exception, control is immediately given to the catch-block and flush() and close() will never get hit. It probably won't really matter in THIS case, but in many database situations, that could be a real problem with left-open connections and ResultSets etc. The finally block ALWAYS gets called, so that would be the best place to do your housekeeping.

    While you're at the subject, checkout Javas new try-with-resources, which addresses this construction. Smart people discovered that this is a pattern that all Java programmers follow, so they made it in to a feature:
    The try-with-resources Statement (The Java™ Tutorials > Essential Classes > Exceptions)

    Java Code:
    try(FileWriter fw = new FileWriter(Constants.fileName)) {
            fw.append(Constants.headers);
            fw.append(Constants.originalBody);
             
            System.out.println("File Successfully restored."+ "\n");
    }
    catch (IOException ex){
        System.out.println(Constants.fileNotAccess);
    }
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2™ © 2013

  4. #4
    fredlo2010 is offline Member
    Join Date
    Jan 2014
    Posts
    17
    Rep Power
    0

    Default Re: Best Try/Catch/Finally

    Hi Surfman,

    Thanks a lot for your reply. The way I was think of it was that the only line that could through an exception would be the Filewriter constructor. And once passed that line all was going to "always" be ok. I was wrong. I see clearly now how the third option is the best.

    As for the New Try-with-sources I was reading about it yesterday as I was trying to figure this out and also because NetBeans was forcing me to do it.


    Thanks once again for the help. :)

Similar Threads

  1. ways to use try, catch and finally in a method
    By bigsonny in forum New To Java
    Replies: 10
    Last Post: 06-12-2013, 02:36 PM
  2. Replies: 2
    Last Post: 08-30-2012, 05:51 PM
  3. Try-catch-(finally?) on reading/writing to files
    By Torchi12 in forum New To Java
    Replies: 8
    Last Post: 11-29-2011, 02:42 PM
  4. how to catch two exceptions in one catch()?
    By arnab321 in forum New To Java
    Replies: 1
    Last Post: 11-06-2008, 11:54 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •