试图添加try和catch代码,卡住了

时间:2015-05-24 10:45:05

标签: java try-catch

我需要实现一个try并捕获大约2个代码块。每个人都需要自己。我写的代码。我为它做了一堂课:

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

第二个块与第一个块非常相似,因为它与第一个块在一个单独的类中。

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

1 个答案:

答案 0 :(得分:1)

当您使用抛出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 ?
   }
}