Results 1 to 20 of 20
  1. #1
    teekei is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Default Don't know why I have an error?

    I am getting this error...

    Java Code:
    F:\Lab 08\Employee.java:19: unreported exception MissingNameException; must be caught or declared to be thrown
          setFirstName( first );
                      ^
    F:\Lab 08\Employee.java:20: unreported exception MissingNameException; must be caught or declared to be thrown
          setLastName( last );
                     ^
    F:\Lab 08\Employee.java:21: unreported exception MissingSSNException; must be caught or declared to be thrown
          setSocialSecurityNumber( ssn );
                                 ^
    3 errors
    FOR THIS PROGRAM....

    Java Code:
    public abstract class Employee
    {
      /*
       *	You will need to add a throws clause to the class header.
       *	List each of the exceptions that may be thrown by the constructor
       */
       private String firstName;
       private String lastName;
       private String socialSecurityNumber;
    
       // three-argument constructor
       public Employee( String first, String last, String ssn )
       {
       	/*
       	 *	Before executing each "set" method, test the argument.
       	 *		Example:  if first is a null string, throw the exception indicatign a missing name,
       	 *						else, invoke setFirstName method
       	 */
          setFirstName( first );
          setLastName( last );
          setSocialSecurityNumber( ssn );
    
       } // end three-argument Employee constructor
    
    
       // set first name
    
       	public void setFirstName( String first ) throws MissingNameException
       	{
          	if (first == null)
       		{
       			try
       			{
       				throw new MissingNameException();
       			}
       			catch(MissingNameException missingNameException)
       			{
       				System.out.println(missingNameException);
       			}
       		}
       		else
       		{
       			firstName = first; // should validate
       		} // end method setFirstName
       	}
    
       // return first name
       public String getFirstName()
       {
          return firstName;
       } // end method getFirstName
    
       		// set last name
       	public void setLastName( String last ) throws MissingNameException
       	{
       		if (last == null)
       		{
    			try
       			{
       				throw new MissingNameException();
       			}
       			catch(MissingNameException missingNameException)
       			{
       				System.out.println(missingNameException);
       			}
       		}
       		else
       		{
       			lastName = last; // should validate
       		} // end method setLastName
       	 }
    
       // return last name
       public String getLastName()
       {
          return lastName;
       } // end method getLastName
    
       	// set social security number
       	public void setSocialSecurityNumber( String ssn ) throws MissingSSNException
       	{
       		if (ssn == null)
       		{
       			try
       			{
       				throw new MissingSSNException();
       			}
       			catch (MissingSSNException missingSSNException)
       			{
       				System.out.println(missingSSNException);
       			}
       		}
       		else
       		{
          		socialSecurityNumber = ssn; // should validate
       		} // end method setSocialSecurityNumber
       	}
    
       // return social security number
       public String getSocialSecurityNumber()
       {
          return socialSecurityNumber;
       } // end method getSocialSecurityNumber
    
    
       // return String representation of Employee object
       @Override
       public String toString()
       {
          return String.format( "%s %s\nsocial security number: %s",
             getFirstName(), getLastName(), getSocialSecurityNumber() );
       } // end method toString
    
    
    }// end abstract class Employee

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    You are trying to use methods that throw exceptions in your constructor. There are a few things I will suggest, which I suggested previously. First, you should not be throwing and catching the exception in the same method, there is no point, you may as well just save the time and print an error message. You throw exceptions if the code CAN throw an exception and let the client code handle the exception correctly. SetName should look like this

    Java Code:
    public void setFirstName(String first){
      if(first == null)
        throw new MissingNameException();
      }
      else
        firstName = name;
    }
    Then you would wrap calls to this method in a try catch clause.

    Next, you should not ever use method that can be overridden in a constructor. Instead of using setters in the constructor, access the variables directly. It's safe to do this. If you use a so called "Alien" method(one which can be overridden), you can get unexpected results or broken code from creating a subclass with overridden methods.

  3. #3
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default

    The three methods you are trying to call are declared to throw an exception. This means you have to handle them just as the error message says. Have you covered exception handling (eg try/catch statements) yet?

  4. #4
    teekei is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Default

    I am still getting the same error message with the changes you suggested, is this correct?

    Java Code:
    public abstract class Employee
    {
      /*
       *	You will need to add a throws clause to the class header.
       *	List each of the exceptions that may be thrown by the constructor
       */
       private String firstName;
       private String lastName;
       private String socialSecurityNumber;
    
       // three-argument constructor
       public Employee( String first, String last, String ssn )
       {
       	/*
       	 *	Before executing each "set" method, test the argument.
       	 *		Example:  if first is a null string, throw the exception indicatign a missing name,
       	 *						else, invoke setFirstName method
       	 */
          setFirstName( first );
          setLastName( last );
          setSocialSecurityNumber( ssn );
    
       } // end three-argument Employee constructor
    
    
       // set first name
    
       	public void setFirstName( String first ) throws MissingNameException
       	{
          	if (first == null)
          	{
       				throw new MissingNameException();
          	}
       		else
       		{
       			firstName = first; // should validate
       		} // end method setFirstName
       	}
    
       // return first name
       public String getFirstName()
       {
          return firstName;
       } // end method getFirstName
    
       		// set last name
       	public void setLastName( String last ) throws MissingNameException
       	{
       		if (last == null)
       		{
       			throw new MissingNameException();
       		}
       		else
       		{
       			lastName = last; // should validate
       		} // end method setLastName
       	 }
    
       // return last name
       public String getLastName()
       {
          return lastName;
       } // end method getLastName
    
       	// set social security number
       	public void setSocialSecurityNumber( String ssn ) throws MissingSSNException
       	{
       		if (ssn == null)
       		{
    			throw new MissingSSNException();
       		}
    		else
       		{
          		socialSecurityNumber = ssn; // should validate
       		} // end method setSocialSecurityNumber
       	}
    
       // return social security number
       public String getSocialSecurityNumber()
       {
          return socialSecurityNumber;
       } // end method getSocialSecurityNumber
    
    
       // return String representation of Employee object
       @Override
       public String toString()
       {
          return String.format( "%s %s\nsocial security number: %s",
             getFirstName(), getLastName(), getSocialSecurityNumber() );
       } // end method toString
    
    
    }// end abstract class Employee

  5. #5
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    The problem now is that you are calling unsafe methods from the constructor. These methods can throw an exception so whenever you use them you want to try calling them and handle any exceptions that can occur.

    You can easily fix the constructor to manipulate the instance variables directly

    Java Code:
    public Employee(String firstName, ...){
      this.firstName = firstName;
      ...
    }
    Instead of calling methods, this is safer because it won't be (possibly) broken by inheritance. This is actually important enough to be part of a item in the book "Effective Java", the reason is this:

    If the subclass overrides the method it can cause problems because the subclass first calls the superclass constructor. If you override the method in a subclass to depend on something in the subclass to be instantiated you can cause an error when constructing the super class. Long story short, either make the methods final so they cannot be overridden, or manipulate the variables directly as shown above.

    It's safe to access the variables inside the class without breaking encapsulation because you can test for and ensure that invariants are kept, and it's safe/easier to do this.

  6. #6
    teekei is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Default

    I made the methods final but still the same error message...

    Java Code:
    --------------------Configuration: <Default>--------------------
    F:\Lab 08\Employee.java:19: unreported exception MissingNameException; must be caught or declared to be thrown
          setFirstName( first );
                      ^
    F:\Lab 08\Employee.java:20: unreported exception MissingNameException; must be caught or declared to be thrown
          setLastName( last );
                     ^
    F:\Lab 08\Employee.java:21: unreported exception MissingSSNException; must be caught or declared to be thrown
          setSocialSecurityNumber( ssn );
                                 ^
    3 errors

  7. #7
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Like I said, you don't actually need the methods to be used in the constructor(and shouldn't), if you really are insistent on it, they have to be final and you still must declare that either 1.) the method/constructor can throw an exception, or 2.) handle any thrown exceptions that may occur.

  8. #8
    teekei is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Default

    Oh ok, so I place the try... catch clause in the constructor rather than the methods?

  9. #9
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default

    The line that calls a method that throws an exception needs to be inside a try statement.
    Java Code:
    try {
        methodThatThrowsException();
    } catch(Exception e) {
        // handle exception here
    }

  10. #10
    teekei is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Default

    I just debugged it, all I did was add a throws clause to the constructor and the program compiled.

  11. #11
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Quote Originally Posted by teekei View Post
    Oh ok, so I place the try... catch clause in the constructor rather than the methods?
    Yes, but errors could still occur if you are not weary. Another reason to directly test invariants and set variables. In your employee class, the invariant is that nothing should be null, so you can check for this, and then set the variables.

    Try causing an exception to be thrown immediately and see what happens to the constructed object(anything weird about it?)

    Here is a snippet to demonstrate
    Java Code:
    public class X{
    	private int x;
    	private int y;
    	private int z;
    	
    	public X(int x, int y, int z){
    		try{
    			setX(x);
    			setY(y);
    			setZ(z);
    		} catch(Exception e){
    			e.printStackTrace();
    		}
    	}
    	public void setX(int x) throws Exception{
    		throw new Exception();
    	}
    	public void setY(int y){}
    	public void setZ(int z){}
    	
    	public String toString(){
    		return x + " " + y + " " + z;
    	}
    	public static void main(String[] args){
    		X x = new X(1, 2, 3);
    		System.out.println(x);
    	}
    }
    This demonstrates what can happen and even more warns against methods in constructors.

    Finally, when you do call a dangerous method(one which can throw an exception, you want to try to call the method and be ready to(catch) handle the exception.

    I had a lengthier post, however; my browser ate them :(

  12. #12
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default

    /*
    * Before executing each "set" method, test the argument.
    * Example: if first is a null string, throw the exception indicatign a missing name,
    * else, invoke setFirstName method
    */
    I just read the comment in your constructor. It would seem you are not following the instructions.

  13. #13
    teekei is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Default

    Now I have problems in my main program, here is the program...
    Java Code:
    // test harness
    // test harness
    /*
     *	This test harness will attemp to instantiate 7 objects belonging to sub-classes of
     *	Employee.  The first two methods instantiate complete and proper objects - one each of
     *	HourlyEmployee and SalariedEmployee.  The following methods will attempt to instantiate
     *	mal-formed objects.  Each attempt to instantiate a mal-formed object will result in a
     *	thrown exception and an associated exception message(s).
     */
    
    public class PostTest
    {
       public static void main( String[] args )
       {
          instantiateHourly();		//instantiate a 'good' HourleEmployee
          instantiateSalaried();	//instantiate a 'good' SalarieEmployee
          missingFirstName();		//attempt to instantiate an employee with no first name
          missingLastName();		//attempt to instantiate an employee with no last name
          missingSSN();				//attampt to instantiate an employee missing SSN
          zeroHours();				//attempt to instantiate HourlyEmployee with 0 hours worked
          overHours();				//attempt to instantiate HourlyEmployee with >84.0 hours worked
    
       } // end main
    
       public static void instantiateHourly()
       {
       	// Output message indicating which instantiation is beind attempted
       	System.out.println( "\nInstantiating a proper Hourly Employee" );
    
       	try
       	{
       		HourlyEmployee Lisa = new HourlyEmployee( "Lisa", "Wilson", "444-44-4444", 40.00, 2.50 );
       	}
       	// catch blocks for each of the exceptions that might occur when instantiate an HourlyEmployee
      	  catch( MissingNameException badName)
          {
          	System.out.println( badName.getMessage() );
          }
          catch( MissingSSNException badSSN )
          {
          	System.out.println( badSSN.getMessage() );
          }
          catch( InvalidHoursWorkedException  badHrs )
          {
          	System.out.println( badHrs.getMessage() );
          }
       }
    
       public static void instantiateSalaried()
       {
       	// Output message indicating which instantiation is beind attempted
       	System.out.println( "\nInstantiating a proper Salaried Employee" );
    
       	try
       	{
       		SalariedEmployee John = new SalariedEmployee( "John", "Smith", "111-11-1111", 800.00 );
       	}
     	 // catch blocks for each of the exceptions that might occur when instantiate a SalariedEmployee
      	  catch( MissingNameException badName)
          {
          	System.out.println( badName.getMessage() );
          }
          catch( MissingSSNException badSSN )
          {
          	System.out.println( badSSN.getMessage() );
          }
       }
    
       public static void missingFirstName()
       {
       	// Output message indicating which instantiation is beind attempted
       	System.out.println( "\nInstantiating an Employee with no first name" );
    
       	try
       	{
       		SalariedEmployee noFirst = new SalariedEmployee( "", "Barnes", "888-88-8888", 1200.00 );;
       	}
      	  // catch blocks for each of the exceptions that might occur when instantiate a SalariedEmployee
      	  catch( MissingNameException badName)
          {
          	System.out.println( badName.getMessage() );
          }
          catch( MissingSSNException badSSN )
          {
          	System.out.println( badSSN.getMessage() );
          }
       }
    
       public static void missingLastName()
       {
       	// Output message indicating which instantiation is beind attempted
       	System.out.println( "\nInstantiating an Employee with no last name" );
    
       	try
       	{
       		HourlyEmployee noLast = new HourlyEmployee( "Jim", "", "222-22-2222", 40.00, 12.50 );
       	}
          // catch blocks for each of the exceptions that might occur when instantiate an HourlyEmployee
      	  catch( MissingNameException badName)
          {
          	System.out.println( badName.getMessage() );
          }
          catch( MissingSSNException badSSN )
          {
          	System.out.println( badSSN.getMessage() );
          }
          catch( InvalidHoursWorkedException  badHrs )
          {
          	System.out.println( badHrs.getMessage() );
          }
       }
    
       public static void missingSSN()
       {
       	// Output message indicating which instantiation is beind attempted
       	System.out.println( "\nInstantiating an Employee with no SSN" );
    
       	try
       	{
       		SalariedEmployee noSSN = new SalariedEmployee( "Ron", "Donald", "", 1200.00 );
       	}
       	// catch blocks for each of the exceptions that might occur when instantiate a SalariedEmployee
       	  catch( MissingNameException badName)
          {
          	System.out.println( badName.getMessage() );
          }
          catch( MissingSSNException badSSN )
          {
          	System.out.println( badSSN.getMessage() );
          }
       }
    
       public static void zeroHours()
       {
       	// Output message indicating which instantiation is beind attempted
       	System.out.println( "\nInstantiating an Hourly Employee with zero hours" );
    
        try
       	{
       		HourlyEmployee zeroHours = new HourlyEmployee( "Max", "Headroom", "321-88-4563", 0.00, 22.50 );
       	}
       	  // catch blocks for each of the exceptions that might occur when instantiate an HourlyEmployee
      	  catch( MissingNameException badName)
          {
          	System.out.println( badName.getMessage() );
          }
          catch( MissingSSNException badSSN )
          {
          	System.out.println( badSSN.getMessage() );
          }
          catch( InvalidHoursWorkedException  badHrs )
          {
          	System.out.println( badHrs.getMessage() );
          }
       }
    
    
       public static void overHours()
       {
       	// Output message indicating which instantiation is beind attempted
       	System.out.println( "\nInstantiating an Hourly Employee with > 84 hours" );
    
       	try
       	{
       		HourlyEmployee overHours = new HourlyEmployee( "Millie", "Smith", "666-66-6666", 100.00, 52.50 );
       	}
       	  // catch blocks for each of the exceptions that might occur when instantiate an HourlyEmployee
      	  catch( MissingNameException badName)
          {
          	System.out.println( badName.getMessage() );
          }
          catch( MissingSSNException badSSN )
          {
          	System.out.println( badSSN.getMessage() );
          }
          catch( InvalidHoursWorkedException  badHrs )
          {
          	System.out.println( badHrs.getMessage() );
          }
       }
    
    } // end class PostTest
    HERE IS THE PROBLEMS...
    Java Code:
    F:\Lab 08\PostTest.java:59: exception MissingNameException is never thrown in body of corresponding try statement
      	  catch( MissingNameException badName)
      	  ^
    F:\Lab 08\PostTest.java:63: exception MissingSSNException is never thrown in body of corresponding try statement
          catch( MissingSSNException badSSN )
          ^
    F:\Lab 08\PostTest.java:79: exception MissingNameException is never thrown in body of corresponding try statement
      	  catch( MissingNameException badName)
      	  ^
    F:\Lab 08\PostTest.java:83: exception MissingSSNException is never thrown in body of corresponding try statement
          catch( MissingSSNException badSSN )
          ^
    F:\Lab 08\PostTest.java:123: exception MissingNameException is never thrown in body of corresponding try statement
       	  catch( MissingNameException badName)
       	  ^
    F:\Lab 08\PostTest.java:127: exception MissingSSNException is never thrown in body of corresponding try statement
          catch( MissingSSNException badSSN )
          ^
    6 errors
    Is it because I named the objects differently in my subclass? just wondering....

  14. #14
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default

    Now you have the opposite. You have included a try/catch statement for an Exception that will never be thrown.

  15. #15
    teekei is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Default

    Where at? My main program or the subclass? Would it help if I posted my other subclasses?

  16. #16
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default

    Quote Originally Posted by teekei View Post
    Where at?
    Where all those error messages say they are. They provide details for a reason. Details such as the line number and the exact line of code.

  17. #17
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    It depends what your subclasses look like, the sub classes constructor will call the super class constructor, so your subclass constructor becomes an exception throwing constrctor(guessing, haven't seen the subclasses).
    Last edited by sunde887; 07-08-2011 at 08:22 AM.

  18. #18
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,006
    Rep Power
    20

    Default

    Quote Originally Posted by Junky View Post
    I just read the comment in your constructor. It would seem you are not following the instructions.
    I was going to post that as I read through this thread.
    The instructions in the constructor are pretty clear that the test and throwing the relevant exception should all be done in the constructor.

    All the rest is fluff...

  19. #19
    teekei is offline Member
    Join Date
    May 2011
    Posts
    39
    Rep Power
    0

    Default

    So should I put the try...catch clause in the constructor?

  20. #20
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default

    Read the comment in the contructor. I assume it was placed there by the teacher. It is clear what you have to do.

Similar Threads

  1. java out of memory error-heap space error
    By elsanthosh in forum NetBeans
    Replies: 4
    Last Post: 06-15-2010, 09:31 AM
  2. Replies: 1
    Last Post: 03-10-2010, 01:53 PM
  3. Replies: 1
    Last Post: 12-05-2009, 07:28 AM
  4. Replies: 1
    Last Post: 10-26-2009, 04:38 PM
  5. Replies: 3
    Last Post: 01-23-2009, 08:53 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
  •