I am having trouble understanding exception handling, unfortunately it just really confuses me. So, I have to implement exception codes that have been created by my teacher in another code with try and catch blocks. I understand the majority of the try and catch blocks, but I don't know how to use the exceptions that have been created and print out the informtation in their constructors. This is one of the excpetions that she created

public class InvalidHoursWorkedException extends Exception
{
   /**
    * No-arg constructor
    */

   public InvalidHoursWorkedException()
   {
      super("\nInvalid Hours Worked");
   }

   /**
    * The following constructor accepts the employee's SSN
    * as an argument.  The SSN will be displayed in the error message
    * for the exception.
    */

   public InvalidHoursWorkedException(String ssn)
   {
      super("\nHours Worked are <1.0 or >84.0 Employee cannot be processed: " + ssn );
   }
}

and this is the program that I have to put the try and catch blocks in. As you can see I tried to start it and I know I need an if statement for the hours worked, but I am lost on the placement of it I suppose and how to have the information printed in the exception constructor

/*
 * HourlyEmployee
 */

public class HourlyEmployee extends 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 double hrsWorked;
   private double hrlyRate;

//   private double weeklyPay;  // hourly pay per week

   // five-argument constructor -- additional arguments are hours worked & hourly rate
   public HourlyEmployee( String first, String last, String ssn,
      double hours, double rate ) throws InvalidHoursWorkedException
   {
      super( first, last, ssn ); // pass to Employee constructor
    /*
     * Before executing each "set" method for hours worked, test the argument.
     * If hours worked does not fall into the proper range, throw the associated exception,
     *  else, execute the set method.
     */
      try
      {

      if(hrsWorked > 0 & <= 84)
      {
            setHrsWorked( hours ); // validate & store hours worked this week
      setHrlyRate( rate );  // validate & store hourly rate
      }

      catch(InvalidHoursWorkedException invalidHoursWorkedException)
      {
        System.err.printf("%s\n", invalidHoursWorkedException.getMessage(ssn);

   } // end of five item constructor

   //set hours worked
   public void setHrsWorked( double hours )
   {
     hrsWorked = hours;
   }

   //return hours worked
   public double getHrsWorked()
   {
     return hrsWorked;
   } // end return hours worked

   //set hourly rate
   public void setHrlyRate( double rate )
   {
     hrlyRate = rate;
   } // end set hourly rate

   //return hourly rate
   public double getHrlyRate()
   {
     return hrlyRate;
   } //end return hourly rate

   // calcualte weekly pay
   public double calcWeeklyPay( double hrsWorked, double hrlyRate )
   {
      return hrsWorked * hrlyRate;

   } // end method calcWeeklyPay

   // return String representation of HourlyEmployee object

   @Override
   public String toString()
   {
     return String.format( "\nHourly Employee: %s\n%s: %.2f %s $%.2f",
          super.toString(), "Hours worked", getHrsWorked(), " at rate ", getHrlyRate() );

   } // end method toString
} // end class HourlyEmployee

I am sorry if it's a lot, but this just goes right over my head.

Recommended Answers

All 14 Replies

I moved the if statement to the setHrsWorked method, so it looks like this now, but I am still stuck

public void setHrsWorked( double hours ) throws InvalidHoursWorkedException 
   {
     if(hours > 0 && hours <= 84)
       try
     {
     hrsWorked = hours;
   }
    catch(InvalidHoursWorkedException invalidHoursWorkedException)
      {
        invalidHoursWorkedException(ssn);
      }
   }

An IF statement by itself won't direct your code to the exception because failing the IF statement isn't an exception. You need to THROW the exception but not quite as you have it there. You want to throw the exception if the IF statement fails.

When you declare a method, if it throws an exception of some kind, you don't have to use the try/catch block, if its not decleared that it throws an exception then you use try/catch. I'd rather use try/catch in most cases as you can print the strack trace of the exection in the catch, which will help you find/fix your error faster.

In your case what you want to see if it throws an exeption is the if statement itself. Also in the catch block you want to exceptionObject.printStackTrace()

Well, the teacher wants us to use the try and catch blocks, but I adjusted the code, but do I use the try and catch block in the actual set method or do I put it in the constructor because she wants us to pass a ssn variable, and i can't pass it in the set method, it's says it cant recognize that variable, but it will in the constructor.

This is how I have it now, it compiled and didn't give me any errors in my post-test program, but I can't run that yet, because I have a another program to add exceptions to.

public HourlyEmployee( String first, String last, String ssn,
      double hours, double rate ) throws InvalidHoursWorkedException
   {
      super( first, last, ssn ); // pass to Employee constructor


       try
       {
      setHrsWorked( hours ); // validate & store hours worked this week
      throw new InvalidHoursWorkedException(ssn);
       }

        catch(InvalidHoursWorkedException invalidHoursWorkedException)
      {
        System.err.printf(invalidHoursWorkedException.getMessage());
      }

       setHrlyRate( rate );  // validate & store hourly rate

   }// end of five item constructor

and here is were I put the if statement

 public void setHrsWorked( double hours ) 
   {
   if(hours > 0 && hours <= 84)
   hrsWorked = hours;
   }

I am sure this is very wrong,but I don't know how to pass the variable ssn through the InvalidHoursWorkedException constructor in the set method.

Normally the throws and the try/catch are in different methods as in

void method1() throws Exception {
  ...
  if (...) 
     // there's a problem that I can't fix...
     throw new Exception ("Sorry, it's gone wrong");
  }
  ...
}

void method2() {
  ...
  try {
     method1();
  catch(Exception e) {
     // I tried to use method1, but it's gome wrong
     display some kind of error message
  }
  ...
}

So, don't have the throws and catch in the constructor? Sorry, like I said this goes right over my head for some reason, confuses me. I need to make sure the hours are a certain amount and if not then throw an exception, so would I use it with the set and get methods then? I tried to have it like this, but I couldn't pass the variable ssn through the exception, like she wants.

public void setHrsWorked( double hours ) throws InvalidHoursWorkedException
   {
   if(hours > 0 && hours <= 84)
     try
   {
   hrsWorked = hours;
    throw new InvalidHoursWorkedException();
   }

      catch(InvalidHoursWorkedException invalidHoursWorkedException)
      {
        System.err.printf(invalidHoursWorkedException.getMessage());
      }
   }

In your set you just need to check the hours and throw an exception if they are invalid. Your exception class has a constructor that includes the ssn, so just call that (using the ssn variable that you already have) to create an exception object to throw.

If you call that set method from your constructor you must either (a) try/catch the exception or (b) declare your constructor as throws the exception and let Java pass the exception on to whoever called your constructor. Option (b) makes more sense here.

Finally - you will have some code somewhere that calls your constructor or your set method. That's where you need to use try/catch so you can catch the exception and issue a suitable error message to the user.

[remember that the HourlyEmployee class may be called from a command line app, a GUI, a web server, a database app... so it has no idea of how to tell the user about an error. All it can do is create an exception and throw that up to the GUI or web server or whatever where it knows how to tell the user]

This is what I did so far, I am trying, thanks for the help so far.

  public HourlyEmployee( String first, String last, String ssn,
      double hours, double rate ) throws InvalidHoursWorkedException
   {
      super( first, last, ssn ); // pass to Employee constructor


       try
       {
      setHrsWorked( hours ); 
       }
       catch(InvalidHoursWorkedException invalidHoursWorkedException)
       {
          System.err.printf(invalidHoursWorkedException.getMessage());
       }
     // validate & store hours worked this week

       setHrlyRate( rate );  // validate & store hourly rate

   }// end of five item constructor

and the set method, but I still can't pass the ssn variable, it says it can't recognize it for some reason

 public void setHrsWorked( double hours )  throws InvalidHoursWorkedException 
   {
   if(hours < 0 && hours > 84)
       throw new InvalidHoursWorkedException();
   else
   {
   hrsWorked = hours;

   }
   }

And her post test has all the get.Message methods, so I am just setting up the exceptions.

Your set method looks great.
Because you have declared the constructor as "throws InvalidHoursWorkedException" you don't need to try/catch it in the constructor. Just call the set method and if that throws the exception then your constructor will automatically pass that on to whoever called the constructor.

You didn't post the code that used the ssn, so I can't comment on that.

So, I don't need to add the try and catch methods? And in the original code I used , where the exception was created it shows that the String ssn is supposed to be passed, but when I use it like this in the set method , throw new InvalidHoursWorkedException(String ssn) or just plain ssn, it doesn't work. It'll work if I use it in the constructor.

So, she wants the try and catch blocks in the code, and she wants us to throw an exception in the class header too, but when I do that it doesn't compile.I also have another code SalariedEmployee that extends my Employee class that throws exceptions, since it extends the Employee class that throws exception, do I need to implement any exceptions in that class either?
This is new code now, still can't pass the ssn variable for some reason

 public HourlyEmployee( String first, String last, String ssn,
      double hours, double rate ) throws InvalidHoursWorkedException, MissingNameException, MissingSSNException
   {
      super( first, last, ssn ); // pass to Employee constructor
    /*
     * Before executing each "set" method for hours worked, test the argument.
     * If hours worked does not fall into the proper range, throw the associated exception,
     *  else, execute the set method.
     */

       try
       {
      setHrsWorked( hours ); 
       }
       catch(InvalidHoursWorkedException invalidHoursWorkedException)
       {
         throw new InvalidHoursWorkedException(ssn); 

       }
     // validate & store hours worked this week

       setHrlyRate( rate );  // validate & store hourly rate

   }// end of five item constructor

   //set hours worked
   public void setHrsWorked( double hours )  throws InvalidHoursWorkedException
   {
   if(hours < 0 && hours > 84)
       throw new InvalidHoursWorkedException();
   else
   {
   hrsWorked = hours;

   }
   }

I had to throw more exceptions becuase of my other class employee throws those for certain methods.

I figured it out!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.