0

Hi I'm supposed to make a Java Programm for school and I'm stuck creating a function that throws a custom exception.

public class ParkingSpace implements ParkingPlace {
    private Automobile P_Car;
    public void placeCar(Car car) throws NoFreePlaceException{
        if(this.P_Car == null) {
            throw new NoFreePlaceException(car);
        }
        this.P_Car = (Automobile) car;
    }
}

The custom exception:

public class NoFreePlaceException extends Exception {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public NoFreePlaceException() {
        super("There is no free place for the current car");
    }

    public NoFreePlaceException(Car car) {
        super ("There is no free place for the current car with plate number: " + car.getLicensePlateNumber());
    }
}

But I always get an Error trying to type this.

Exception NoFreePlaceException is not compatible with throws clause in ParkingPlace.placeCar(Car) ParkingSpace.java
/NOS_LB2/src/at/fhsalzburg/its/nos/parksim line 41 Java Problem

I'm supposed to make this implementation just like that according to my Professor. I'm quite versed in C++ but still relatively new to Java.

UkFLSUI
  • 5,509
  • 6
  • 32
  • 47
Stephan Pich
  • 171
  • 1
  • 2
  • 11

2 Answers2

2

This error is due to the overridden method's signature does not match the method from the interface.

Just modify placeCar() method in ParkingPlace interface as follows:

void placeCar(Car car) throws NoFreePlaceException
Akshar Patel
  • 8,998
  • 6
  • 35
  • 50
1

Please check your interface sources. The implementations are only allowed to throw more specific exceptions. In your case I believe what you need is

interface ParkingPlace {
    // here it could also be throws Exception
    // but that is considered a bad practice
    void placeCar(Car car) throws NoFreePlaceException;
}

Throwing Exception (and not a specific exception) is a bad practice, because they also cover all sorts of runtime errors (unchecked exceptions), which in most cases should not be handled in your business logic code. In general I would strongly recommend reading about exceptions in Java as it is one of the most important topics.

Guide on Java exceptions

Java: checked vs unchecked exception explanation

Nestor Sokil
  • 2,162
  • 12
  • 28