java - throw 和 catch 子句

标签 java exception

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

    * 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

   }

我感觉我的设置方法仍然处于关闭状态

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

   }
   }

最佳答案

好吧,这就是您想要自己实现其他逻辑的内容

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

关于java - throw 和 catch 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24392803/

相关文章:

java - "Manifest merger failed : uses-sdk:minSdkVersion 9 cannot be smaller than version 14"是什么意思

java - sendRedirect() 和 ObjectOutputStream 之间的 IllegalStateException

c# - 抛出正确类型的异常

java - Try-Catch 中的静态方法未完全执行

java - 如何从java异常中获取唯一原因

java - 主键值在 Spring boot 中得到更新

java - 将一个键值映射到 Map 中另一个键值的算法

java - GUI 保留方程

javascript - 将 'unhandled' 网络 worker 异常标记为已处理

java - TestNG异常: Cannot Instantiate class