Reputation: 49
I need to implement a try and catch around 2 blocks of code. each need there own. code that I have written. I have made a class for it:
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;
}
}
second blockis very similar to the first as this is in a separate class to the first.
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;
}
Upvotes: 0
Views: 65
Reputation: 364005
When you use a method that throws an Exception
you have to use the keywords throws
(unless you throw a RuntimeException. These do not have to be declared this way). In this way, the other methods that call this method can handle the exception.
You can use something like this:
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");
}
//....
}
}
When you call the submitOffer()
method you can use:
public void myMethod() throws OfferException{
MyClass.submitOffer();
}
or
public void myMethod(){
try{
MyClass.submitOffer();
} catch( OfferException oe){
//handle here the exception
}
}
Also if you are using a custom Exception
you should call the super constructor.
public class OfferException extends Exception{
String message;
public OfferException(String message){
super(message); //call the super constructor
this.message = message; //Do you need it ?
}
}
Upvotes: 1