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() {
开发者_StackOverflow中文版 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 have to catch it somewhere, or your application will quit showing (or logging) that exception's stacktrace.
It is up to you, though, where exactly you catch them. Basically, you should catch them where you can do something about them, such as change your input data, ask user for another input or just notify the user of the error.
Syntactically its ok to do that, but now the one who calls the Constructor of Vehicle has to worry about the Exception, so you should think about if it is semantically correct. in this example it could be acceptable to propagate the exception, since the constructor takes an initial speed, which could be negative. If this wasnt the case, i would catch the Execption instead
A checked exception in Java gets propagated until one of these things happen:
- The exception gets caught in a catch block
- The main() method is reached (if it's not caught at this point, the JVM crashes)
- An uncaught exception handler was defined and catches the exception (see http://stuffthathappens.com/blog/2007/10/07/programmers-notebook-uncaught-exception-handlers)
Notice that an unchecked exception (that is, an exception that extends from RuntimeException) will also get propagated unless explicitly caught
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.
精彩评论