尝试将 try 和 catch 添加到代码中,卡住

Trying to add try and catch to code, stuck

我需要实现一个 try 和 catch 大约 2 个代码块。每个人都需要自己。我写的代码。我为它做了一个class:

public boolean makeOffer(int offer) throws OfferException
{
  // reject offer if sale is not open for offers
  if (this.acceptingOffers == false)
  {
     return false;
  }

  // reject offer if it is not higher than the current highest offer
  else if (offer <= this.currentOffer)
  {
     throw new OfferException("Offer not High enough!");
  }

  else
  {
     // new offer is valid so update current highest offer
     this.currentOffer = offer;

     // check to see if reserve price has been reached or exceeded
     if (this.currentOffer >= this.reservePrice)
     {
        // close the Sale if reserve has been met
        this.acceptingOffers = false;
     }

     return true;
  }
}

第二个区块与第一个非常相似,因为它与第一个 class 分开。

public boolean makeOffer(int offer)
{
  // reject offer if sale is not open for offers
  if (this.acceptingOffers == false)
  {
     return false;
  }

  // reject offer if it is not higher than the current highest offer
  else if (offer <= this.currentOffer)
  {
     return false;
  }

  else
  {
     // new offer is valid so update current highest offer
     this.currentOffer = offer;

     // check to see if reserve price has been reached or exceeded
     if (this.currentOffer >= this.reservePrice)
     {

        System.out.println("Name of the Highest Bidder: ");

        Scanner s = new Scanner(System.in);
        this.highestBidder = s.nextLine();

        s.close();
        this.acceptingOffers = false;
     }
     return true;
  }

当您使用抛出 Exception 的方法时,您必须使用关键字 throws(除非您抛出 RuntimeException。这些不必以这种方式声明) .这样其他调用这个方法的方法就可以处理异常了。

你可以这样使用:

private static void submitOffer() throws OfferException{

 // ...
 if ( sales[i].getSaleID().equalsIgnoreCase(saleID)){   

    //try {  Remove this try
    offerAccepted = sales[i].makeOffer(offerPrice);
    if (offerAccepted == true){
       System.out.print("Offer was accepted"); 
       if(offerPrice <= sales[i].getReservePrice()){
             System.out.print("Reserve Price was met");
       }else{
          throw new OfferException("Resever not met!");
       }
    }else{
       throw new OfferException("Offer was Not accepted");
    }

    //....

}

}

调用submitOffer()方法时可以使用:

public void myMethod() throws OfferException{
  MyClass.submitOffer();
}

public void myMethod(){
  try{
    MyClass.submitOffer();
  } catch( OfferException oe){
     //handle here the exception
  }
}

此外,如果您使用自定义 Exception,您应该调用超级构造函数。

public class OfferException extends Exception{

   String message;

   public OfferException(String message){
        super(message); //call the super constructor
        this.message = message;   //Do you need it ?
   }
}