投掷和捕捉条款

时间:2014-06-24 17:28:08

标签: java exception

我无法理解异常处理,遗憾的是它真的让我很困惑。因此,我必须使用try和catch块实现由我的老师在另一个代码中创建的异常代码。我理解大多数try和catch块,但我不知道如何使用已创建的异常并在其构造函数中打印出信息。这是她创建的例外之一

    * This exception should be used when the hours worked value for an hourly employee
     * is found to be less than 1 or greater than 84.
     *
     * When using this exception, if at all possible, pass a String containing employee SSN
     *  to the constructor.  The SSN will then be displayed as part of the exception      message,
     *  thus allowing the invalid record to be more easily located.
     */

     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 );
   }
}

这就是我到目前为止所拥有的。我不知道它是否正确,也不知道如何在InvalidHoursWorkedException的set方法中传递ssn变量。

 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
       {
      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

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

   }
   }

这是一些评论后改变的代码。我仍然不知道是否需要在构造函数头和set方法头中抛出异常

  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
       {
      setHrsWorked( hours ); 
       }
       catch(InvalidHoursWorkedException invalidHoursWorkedException)
       {
         throw new InvalidHoursWorkedException(ssn); 

       }
     // validate & store hours worked this week

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

   }

我觉得我的set方法仍然关闭

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

   }
   }

3 个答案:

答案 0 :(得分:1)

好的,这就是你想要自己实现其他逻辑

public class HourlyEmployee extends Employee

{
    private double hrsWorked;
    private double hrlyRate;

    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.out.println(invalidHoursWorkedException.getMessage());
        }
        // 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;
            System.out.println("Hours set to "+hrsWorked);

        }
    }
    public static void main(String arr[])
    {
        try {
            HourlyEmployee h = new HourlyEmployee("abc","def","xyz",100,10);
        } catch (InvalidHoursWorkedException e) {
            System.out.println(e.getMessage());
        }
    }
}

答案 1 :(得分:0)

当您希望方法的调用者知道它可能抛出的异常时,您会在方法中提及抛出。但是你的情况是你在catch子句中捕获异常,所以你不必在你的方法中提到抛出。因为它永远不会抛出

答案 2 :(得分:0)

您的HourlyEmployee的一个构造函数声明它能够抛出InvalidHoursException,如果小时数小于0或大于84,则会执行此操作。

每当您调用setHours时,如果小时未通过验证,则抛出该异常。注意也可以从一个构造函数中调用setHours。

InvalidHoursException继承自Exception,因此为了捕获它,您可以捕获所有异常。如果你需要它做一些特殊的事情,你可以在一个块中捕获InvalidHoursException,在另一个块中捕获泛型异常。

对于消息,您可以看到对超级(消息)重载的调用。要获取该消息,只需在InvalidHoursException实例上调用.getMessage()。

像这样......

try{
    HourlyEmployee hrEmp = new HourlyEmployee("John", "Smith", "123-45-6789", 85, 500.00)
}
(catch InvalidHoursException ihe){
    String message = ihe.getMessage();
    // do something with message here...
}
相关问题