6 Replies - 2183 Views - Last Post: 20 September 2012 - 12:40 PM Rate Topic: -----

#1 scy0846  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 68
  • Joined: 03-October 11

Try/Catch problem and making my own error exception.

Posted 19 September 2012 - 08:16 PM

Ok I had started this in the middle of another thread but I figured it might be more helpful to others with it being under the proper thread title.

I am trying to implement a Try/Catch to catch a NumberFormatException, but it is not working like I expected. It is catching the exception, but it won't let me use variables or any other data that did not have an error in it. Without the try/catch my program works if I delete the line that has the exception(so I don't get a java error and it stops). When my program runs with the try catch it doesn't produce any output because it won't work like the program should. It's reading text from a file and creating an object array from the file.

my try catch is supposed to catch the exception and print it on a file. and then I have to create my own exception, but I'm not sure how to implement it. I know the exception will use myStates[index].getRegionNumber()==2 as the error.

public class StateController 
{
    private States[] myStates;
    private int numStates = 0;

    public StateController(int maxSize) 
    {
        myStates = new States[maxSize];
    } // end stateController()
    
    
    /**
     * Routine for loading data into the array of States from "statesarray2.txt".
     *
     * @param filename 
     * @throws IOException
     * @param name
     * @param cap
     * @param abbr
     * @param pop
     * @param reg
     * @param regnum
     * @return array of States objects from statesarray2.txt 
     */
    public void loadData(String filename) throws IOException 
    {
        FileInputStream fis1 = new FileInputStream("statesarray2.txt"); 
        //obtains file statearray.txt
        BufferedReader br1 = new BufferedReader(new InputStreamReader(fis1)); 
        //reads statearray.txt
        int regnum, pop;
        String name, cap, abbr, reg;

        String inputString;
        inputString = br1.readLine();

        while (inputString != null) 
            //while loop to continually create state objects
        
           {
            try
            {
                name = inputString.substring(0, 15).trim(); 
                //parses the file for name
                cap = inputString.substring(15, 30).trim(); 
                //parses the file for capital
                abbr = inputString.substring(30, 32).trim(); 
                //parses the file for state abbreviation
                pop = Integer.parseInt(inputString.substring(32, 40).trim()); 
                //parses the file for population
                reg = inputString.substring(40, 55).trim(); 
                //parses the file for region
                regnum = Integer.parseInt(inputString.substring(55, 56).trim()); 
                //parses the file for region number

                myStates[numStates] = new States(name, cap, abbr, pop, reg, regnum); 
                //creates a new state object with attributes
                numStates++; //increases state count
                inputString = br1.readLine();
            }
            catch (NumberFormatException exc)
            {
                String file  =  "errorfile.2.txt"; // name your output file
                FileWriter fw = new FileWriter (file);     
                // creates object fw of type FileWriter.   
                BufferedWriter bw = new BufferedWriter (fw);  
                // creates object bw of type ...
                PrintWriter outFile = new PrintWriter (bw);  
                // creates object outFile of type ..

                outFile.println (exc);	// writes this as a stream.  Try it!
                outFile.println ("BAD INPUT\nInvalid Population Value" ); 		
                //  prints a blank line in the file

                outFile.close();
            }
            catch ( ex2)
            {
                //create error exception here regionNumber cannot equal 2 or 4
            }
        } // end while (inputString != null) 
        br1.close();
    }//end loadData(String filename) throws IOException



file is
Pennsylvania   Harrisburg     PA12001451Middle_Atlantic2
New_Jersey     Trenton        NJ 8115011Middle_Atlantic2
Maryland       Annapolis      MD 5134808Middle_Atlantic2
West_Virginia  Charleston     WV 18Q1156Middle_Atlantic2
Delaware       Dover          DE  743603Middle_Atlantic2
Virginia       Richmond       VA 67a1345Middle_Atlantic2
North_Carolina Raleigh        NC 7546493South          3
South_Carolina Columbia       SC 3835962South          3
Tennessee      Nashville      TN 5430621South          3
Maine          Augusta        ME 1244250New_England    1
Texas          Austin         TX19759614Southwest      5
New_Mexico     Santa_Fe       NM 1736931Southwest      5
Arizona        Phoenix        AZ 4668631Southwest      5
Washington     Olympia        WA 5689263West           6
Oregon         Salem          OR 3281974West           6
Massachusetts  Boston         MA 6147132New_England    1
Connecticut    Hartford       CT 3274069New_England    1
Rhode_Island   Providence     RI  988480New_England    1
New_York       Albany         NY18146200Middle_Atlantic2
Vermont        Montpelier     VT  588632New_England    1
New_Hampshire  Concord        NH 1185048New_England    1
Georgia        Atlanta        GA 7642207South          3
Illinois       Springfield    IL12425326Midwest        4
Wisconsin      Madison        WI 5A23500Midwest        4
Minnesota      St_Paul        MN 4725419Midwest        4
Iowa           Des_Moines     IA 2862447Midwest        4
Missouri       Jefferson_City MO 5438559Midwest        4
North_Dakota   Bismark        ND  638244Midwest        4
South_Dakota   Pierre         SD  738171Midwest        4
Nebraska       Lincoln        NE 1662719Midwest        4
Kansas         Topeka         KS 2629067Midwest        4
Oklahoma       Oklahoma_City  OK 3346713Southwest      5
California     Sacramento     CA32182118West           6
Idaho          Boise          ID 1228684West           6
Montana        Helena         MT  880453West           6
Wyoming        Cheyenne       WY  480907West           6
Nevada         Carson_City    NV 1746898West           6
Utah           Salt_Lake_City UT 2099758West           6
Colorado       Denver         CO 3970971West           6
Alaska         Juno           AK  614010West           6
Hawaii         Honolulu       HI 1193001West           6
Florida        Tallahassee    FL14915980South          3
Alabama        Montgomery     AL 4351999South          3
Mississippi    Jackson        MS 2752092South          3
Arkansas       Little_Rock    AR 2538303South          3
Louisiana      Baton_Rouge    LA 4368967South          3
Kentucky       Frankfort      KY 3936499South          3
Ohio           Columbus       OH 3346713Midwest        4
Michigan       Lansing        MI 9817242Midwest        4
Indiana        Indianapolis   IN 5899195Midwest        4


Is This A Good Question/Topic? 0
  • +

Replies To: Try/Catch problem and making my own error exception.

#2 scy0846  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 68
  • Joined: 03-October 11

Re: Try/Catch problem and making my own error exception.

Posted 19 September 2012 - 08:22 PM

ah nevermind I used a finally statement with the readline and it worked!
Was This Post Helpful? 0
  • +
  • -

#3 scy0846  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 68
  • Joined: 03-October 11

Re: Try/Catch problem and making my own error exception.

Posted 19 September 2012 - 10:01 PM

I am having a hard time figuring out how to make my own error exception. I created an extended class of Exception, but I guess I'm not completely sure how to set the parameters also I cannot get the NumberFormatException to repeat the Exception Catch. When I open the output file it only shows the first one that is until RegionNumberException overwrites it with nothing creating a blank file. It's just not working.


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package project2mitchell;

/**
 *
 * @author Taylor
 */
public class RegionNumberException extends Exception
{
  public RegionNumberException(String msg)
  {
      super(msg);
  }

    RegionNumberException() {
        throw new UnsupportedOperationException("Not yet implemented");
    }
}




public void loadData(String filename) throws IOException, RegionNumberException 
    {
        FileInputStream fis1 = new FileInputStream("statesarray2.txt"); 
        //obtains file statearray.txt
        BufferedReader br1 = new BufferedReader(new InputStreamReader(fis1)); 
        //reads statearray.txt
        int regnum, pop;
        String name, cap, abbr, reg;

        String inputString;
        inputString = br1.readLine();

        while (inputString != null) 
            //while loop to continually create state objects
        
           {
            try
            {
                
                name = inputString.substring(0, 15).trim(); 
                //parses the file for name
                cap = inputString.substring(15, 30).trim(); 
                //parses the file for capital
                abbr = inputString.substring(30, 32).trim(); 
                //parses the file for state abbreviation
                pop = Integer.parseInt(inputString.substring(32, 40).trim()); 
                //parses the file for population
                reg = inputString.substring(40, 55).trim(); 
                //parses the file for region
                regnum = Integer.parseInt(inputString.substring(55, 56).trim()); 
                //parses the file for region number
    
                myStates[numStates] = new States(name, cap, abbr, pop, reg, regnum); 
                //creates a new state object with attributes
                numStates++; //increases state count
                inputString = br1.readLine();
                
                if(myStates[numStates].getRegionNumber()==2) 
                {
                    throw new RegionNumberException();
                }
            }
            
            catch (NumberFormatException ex1)
            {
                String file  =  "errorfile.2.txt"; // name your output file
                FileWriter fw = new FileWriter (file);     
                // creates object fw of type FileWriter.   
                BufferedWriter bw = new BufferedWriter (fw);  
                // creates object bw of type ...
                PrintWriter outFile = new PrintWriter (bw);  
                // creates object outFile of type ..

                outFile.println (ex1);	// writes this as a stream.  
                outFile.println ("BAD INPUT\nInvalid Population Value" ); 		
                //  prints a blank line in the file
                
                outFile.close();
            }
            catch(RegionNumberException ex2)
            {
                String file  =  "errorfile.2.txt"; // name your output file
                FileWriter fw = new FileWriter (file);     
                // creates object fw of type FileWriter.   
                BufferedWriter bw = new BufferedWriter (fw);  
                // creates object bw of type ...
                PrintWriter outFile = new PrintWriter (bw);  
                // creates object outFile of type ..

                outFile.println (ex2);	// writes this as a stream.  
                outFile.println ("BAD INPUT\nInvalid Region Number" ); 		
                //  prints a blank line in the file
                
                outFile.close();
            }
            finally
            {
                inputString = br1.readLine();
            }
        } // end while (inputString != null) 
        br1.close();
    }//end loadData(String filename) throws IOException


I am stuck at this point. I keep getting an error as well

Exception in thread "main" java.lang.NullPointerException
at project2mitchell.StateController.loadData(StateController.java:76)
at project2mitchell.Main.main(Main.java:27)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

Main
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package project2mitchell;

import java.io.IOException;

/**
 *
 * @author Taylor
 */
public class Main {

    /**
     * @param args the command line arguments
     * 
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, RegionNumberException
    {
       // create an array of individual state objects to hold 50 items
        StateController myStateController;
        myStateController = new StateController(50);

        // Call method to retrieve data and store it in the new array
        myStateController.loadData("statesarray2.txt");
        
        // display Original array of stated with a header
        myStateController.displayStates();
        
        myStateController.ArrayList();
        // TODO code application logic here
    }
}


Was This Post Helpful? 0
  • +
  • -

#4 scy0846  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 68
  • Joined: 03-October 11

Re: Try/Catch problem and making my own error exception.

Posted 20 September 2012 - 11:41 AM

anyone have any ideas?
Was This Post Helpful? 0
  • +
  • -

#5 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Try/Catch problem and making my own error exception.

Posted 20 September 2012 - 11:54 AM

Sorry but you missed the concept...

You do not catch an Exception that you throw yourself it is useless.
You throw an Exception when you do not know what to do whith the error and you delegate the problem to the caller.

Integer.parseInt() is a good example
If it receives a a String that it cannot translate into a int it does not know if it is important or not, if it should continue or not, so it simply throws the Exception telling to the caller: "Sorry your String is not an int, I cannot translate it" so now your program facing that Exception can take an appropriate action:
- crashing and aborting
- ignoring the problem
- prompting the user again

So, when you throw and Exception is because you return to the caller

doing
      try {
         ....
         if(condition) 
            throw new MyExceptionType("Something wrong");
         ....
      catch(MyExceptionType met) {
         ... do action1;
         ... do action2;
      }


is completly using resources for nothing and defats the whole concept
simply write
         if(condition) { 
            ... do action1;
            ... do action2;
         }



So basically you never throw an Exception in a try block if you catch it yourself.

Happy coding
Was This Post Helpful? 0
  • +
  • -

#6 scy0846  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 68
  • Joined: 03-October 11

Re: Try/Catch problem and making my own error exception.

Posted 20 September 2012 - 12:25 PM

if(condition) { 
   ... do action1;
   ... do action2;
}




so with this method I wouldn't need the extended class then?

How would I get it to recognize that states with regionNumber 2 and 4 are not to be used or does it just know.
Was This Post Helpful? 0
  • +
  • -

#7 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Try/Catch problem and making my own error exception.

Posted 20 September 2012 - 12:40 PM

I am afraid you just want to throwh an Exception to throw an Exception :) For homework purpose ?

To do it correctly you will have to split your code in separate methods
right now

if(myStates[numStates].getRegionNumber()==2)
simply do what you do in the catch block and break; to exit the while() loop
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1