If I propagate a exception, do I have to eventually catch it later on?
Suppose I have this code:
public class InvalidDataException extends Exception {
public InvalidDataException (String e){
super(e);
}
}
public class Vehicle {
private double speed;
private int vin;
public Vehicle (double nspeed, int nvin) throws InvalidDataException{
setVin(nvin);
setSpeed(nspeed);
}
public double getSpeed() {
return speed;
}
public void setSpeed(double speed) throws InvalidDataException{
if (speed < 1){
throw new InvalidDataException("negative speed: " + speed);
}
this.speed = speed;
}
public int getVin(){
return vin;
}
public void setVin(int speed){
this.vin = speed;
}
}
is this ok or do i have to catch it instead?
You don’t need to catch it yourself, but you probably want to. If you don’t handle it yourself, it’ll continue propagating up to the JVM, at which point it will crash and print the stack trace to standard error.
If the exception is something that your application can handle and recover from, then you’ll obviously need to put a catch statement somewhere that will handle this specific situation.